How to Interact with an API in Python

From Code Self Study Wiki
Jump to: navigation, search

This page contains basic examples of how to interact with an API in Python. Please add more examples to this page.

POST Request

Quick example using the cowsay API.

You'll need requests: pip install requests

>>> import requests
>>> payload = { 'message': 'Saluton, Mondo', 'format': 'text' }
>>> r = requests.post('http://cowsay.morecode.org/say', data=payload)
>>> print(r.text)

Response:

  ______________
< Saluton, Mondo >
  --------------
         \   ^__^ 
          \  (oo)\_______
             (__)\       )\/\
                 ||----w |
                 ||     ||

GET Request

Same as POST request, but use requests.get() instead of requests.post(), and params instead of data:

r = requests.get('http://cowsay.morecode.org/say', params=payload)

You can omit the params if you just want to fetch a webpage or don't otherwise need parameters.

Processing JSON Data

The data you get back from an API will probably be in JSON format. You can convert that JSON to a Python dictionary using json.loads(). Once you have a Python dictionary, you can use Python methods on it.

import json
import requests
 
# Fetch some JSON from an API
response = requests.get('put your API URL here')
 
# Convert the JSON to a Python dictionary using json.loads()
json_data = json.loads(response.text)
 
# Access individual items of the dictionary in the normal Python way:
json_data['some_key']['sub_key']
 
# Find keys like this:
for k in json_data:
    print(k)
 
# or just inspect the json_data variable