Course Outline (Part 37)

An API (Application Programming Interface) allows two applications to talk to each other. When you use an app on your phone, the app connects to the Internet and sends data to a server. The server retrieves that data, interprets it, performs the necessary actions, and sends it back to your phone.

In Python, the easiest way to interact with APIs is using the requests module.


1. requests module

The requests library is not built-in, so you must install it via PIP:

pip install requests

Once installed, import it in your script:

import requests

2. GET request

The GET method indicates that you’re trying to get or retrieve data from a specified resource.

import requests

response = requests.get('https://api.github.com/users/octocat')
print(response.status_code) # 200 means OK

3. Parse JSON response

Most modern APIs return data in JSON format. The requests module has a built-in .json() method that automatically parses the JSON response into a Python dictionary.

import requests

response = requests.get('https://api.github.com/users/octocat')

if response.status_code == 200:
    data = response.json()
    print("Name:", data["name"])
    print("Location:", data["location"])

4. POST request

The POST method means you are submitting data to be processed to a specified resource.

import requests

url = 'https://httpbin.org/post'
my_data = {'key': 'value', 'name': 'John'}

response = requests.post(url, data=my_data)
print(response.text)

If the API expects JSON instead of form data, you can pass the dictionary to the json parameter instead of data:

response = requests.post(url, json=my_data)

5. Headers and parameters

Often, you need to pass additional headers (like authentication tokens) or query parameters.

Query Parameters

You can append query strings to the URL (?key=value), but it is cleaner to use the params keyword argument.

import requests

payload = {'q': 'python', 'sort': 'stars'}
response = requests.get('https://api.github.com/search/repositories', params=payload)

# The URL hit was actually: https://api.github.com/search/repositories?q=python&sort=stars

Headers

To pass custom headers, use the headers keyword argument.

import requests

url = 'https://api.github.com/user'
headers = {'Authorization': 'token YOUR_ACCESS_TOKEN'}

response = requests.get(url, headers=headers)

6. Error handling (status codes)

Good API handling requires checking if the request was successful. You can check the status_code manually, or use the raise_for_status() method which throws an HTTPError exception if the request was not successful (a 4XX client error or 5XX server error).

import requests

try:
    response = requests.get('https://api.github.com/invalid-endpoint')
    response.raise_for_status() # Will raise an exception for 404
except requests.exceptions.HTTPError as err:
    print("HTTP Error occurred:", err)
except Exception as err:
    print("Other error occurred:", err)

Discussion

Loading comments...