Codeskill

Learn to code, step by step

Python and APIs: Interacting with Web Services

Calling web APIs from Python using the requests library.

What is an API?

API stands for Application Programming Interface. It is a set of rules that lets one application talk to another. On the web, APIs give you access to data and services – social feeds, weather, payments, and plenty more – without scraping HTML.

Using Python for API requests

The requests library handles HTTP calls, responses, and parsing. Install it first:

Setting up

pip install requests

Making a GET request

GET retrieves data from a URL:

import requests

url = 'https://api.example.com/data'
response = requests.get(url)

# Check if the request was successful
if response.status_code == 200:
    print(response.json())  # Print the JSON data
else:
    print('Failed to retrieve data')

Understanding response objects

The response object from requests.get() holds everything the server sent back:

  • status_code: the HTTP status code.
  • text: the response body as a string.
  • json(): parses JSON into a Python object.

Handling POST requests

POST sends data to the server to create or update something. The payload goes in the request body:

data = {'key': 'value'}
response = requests.post(url, data=data)

if response.status_code == 200:
    print(response.json())
else:
    print('Failed to post data')

Adding headers

Headers carry metadata – often used for authentication:

headers = {'Authorization': 'Bearer YOUR_ACCESS_TOKEN'}
response = requests.get(url, headers=headers)

Working with JSON data

JSON is the usual format for REST APIs. Python makes it straightforward:

import json

response = requests.get(url)
if response.status_code == 200:
    data = response.json()
    print(json.dumps(data, indent=4))  # Pretty print the JSON data

Error handling

Network problems and HTTP errors happen. Catch them:

try:
    response = requests.get(url)
    response.raise_for_status()
except requests.exceptions.HTTPError as errh:
    print ("Http Error:", errh)
except requests.exceptions.ConnectionError as errc:
    print ("Error Connecting:", errc)
except requests.exceptions.Timeout as errt:
    print ("Timeout Error:", errt)
except requests.exceptions.RequestException as err:
    print ("Oops: Something Else", err)

Using Python with REST APIs

REST APIs use standard HTTP methods (GET, POST, PUT, DELETE), which maps neatly onto requests.

API authentication

Many APIs need an API key or OAuth token. A typical pattern:

api_key = 'YOUR_API_KEY'
headers = {'Authorization': f'Bearer {api_key}'}
response = requests.get(url, headers=headers)

Rate limiting and pagination

Watch for rate limits (how many requests you can make per minute) and pagination (large result sets split across pages). Both are documented in the API’s reference – read that before you loop.

Pick a free API with decent docs, make a GET request, print the JSON, then try POST with a key. That covers most of what you need day to day.

PreviousWeb Scraping with Python: Gathering Data from the Internet