REST APIs on the internet communicate using HTTP. This means that whenever we want to send a REST API some data or receive some data from it, we must do this using HTTP.
In HTTP clients communicate with servers by sending requests; servers respond with responses. When we talk about interacting with a REST API, we are the client. The server is the API we are talking with.
For example, you as a client may communicate with the Twitter API, or with the Facebook API, and so on.
If you are thinking about creating your own API so that clients can communicate with you (for example, your own mobile app), you may be interested in my comprehensive online course.
Sending a request to an API
Let's imagine we have the sample API we want to communicate with, http://api.example.com/
. We could interact with it by sending a HTTP request.
When making a request to a URL like
http://api.example.com/
, everything after the TLD (.com
) is called the endpoint. In this case, the endpoint is/
.
The API documentation will give you information regarding exactly what endpoint to make requests to for specific data.
Making a GET request in Python
You'll have to install the popular requests
library to easily make HTTP requests in Python:
pip install requests
Then, you'll be able to execute a file like the below to make a GET request:
import requests
resp = requests.get('http://api.example.com/')
print(resp.json())
Making a POST request in Python
POST requests are normally used to send data to the server. For example you may send some JSON data:
import requests
payload = {'name': 'Example'}
resp = requests.post('http://api.example.com/', json=payload)
print(resp.json())
You can also include custom headers, if required:
import requests
payload = {'name': 'Example'}
headers = {'Content-Type': 'application/json'}
resp = requests.post('http://api.example.com/', json=payload, headers=headers)
print(resp.json())
You can send form data instead of JSON just by doing requests.post('http://api.example.com/', data={'field': 'value'}
instead.
Usual headers
Most REST APIs will require that you authenticate using an API key. This will normally be included in the URL, the body of the request, or a header. Below are some examples on how to include authorization for an API:
In the URL:
import requests
API_KEY = '123abc'
resp = requests.post('http://api.example.com/?key=' + API_KEY)
print(resp.json())
In the payload:
import requests
payload = {'key': '123abc'}
resp = requests.post('http://api.example.com/', json=payload)
print(resp.json())
In a header:
import requests
headers = {'Authorization': 'Bearer 123abc'} # Having 'Bearer' is common. Check your API documentation to see if it is required!
resp = requests.post('http://api.example.com/', headers=headers)
print(resp.json())