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[edit]

Quick example using the cowsay API.

You'll need requests: pip install requests

>>> import requests
>>> payload = { 'message': 'Saluton, Mondo', 'format': 'text' }
>>> r ='', data=payload)
>>> print(r.text)


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

GET Request[edit]

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

r = requests.get('', params=payload)

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

Processing JSON Data[edit]

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:
# Find keys like this:
for k in json_data:
# or just inspect the json_data variable