Skip to Content

Can Python be used to make a REST API call?


Yes, Python can definitely be used to make REST API calls. Python has several libraries and modules like requests, urllib, and httplib2 that make it easy to interact with REST APIs.

REST (Representational State Transfer) is an architectural style for building web services. REST APIs allow you to access and manipulate resources using HTTP requests like GET, POST, PUT, and DELETE. When you make a request to a REST API, you will get a response back typically in JSON or XML format.

Python, with its simple syntax and vast collection of libraries, is one of the most popular languages used for consuming REST APIs. In this article, we will look at how to make GET and POST requests to REST APIs in Python.

Prerequisites

Before you can start making API calls in Python, you need:

  • Python installed on your machine.
  • Some knowledge of Python syntax and constructs.
  • Access to a REST API you want to use. This can be a public API or an API you have built.

We will be using the requests module in this article. So you need to install it using:

“`
pip install requests
“`

This will allow us to make HTTP requests to access our REST API.

Making a GET Request

The GET method is used to retrieve a resource from a REST API. Here are the steps to make a GET request in Python:

  1. Import the requests module:
  2. “`python
    import requests
    “`

  3. Specify the URL for the API endpoint you want to access. For example:
  4. “`python
    url = ‘https://api.example.com/items/12345’
    “`

  5. Make the GET request and store the response from the API:
  6. “`python
    response = requests.get(url)
    “`

    This sends a GET request to the URL we specified and stores the returned JSON response.

  7. Access data from the JSON response:
  8. “`python
    data = response.json()
    print(data[‘name’])
    “`

    Here we are printing the name key from the JSON response.

So our full Python script to make a GET request will be:

“`python
import requests

url = ‘https://api.example.com/items/12345’

response = requests.get(url)
data = response.json()

print(data[‘name’])
“`

This simple script allows us to make a GET request to access an API and print the returned data.

Making a POST Request

The POST method is used to create a new resource on the server. Here is how to make a POST request in Python:

  1. Import the requests module:
  2. “`python
    import requests
    “`

  3. Specify the URL to make the POST request to:
  4. “`python
    url = ‘https://api.example.com/items’
    “`

  5. Define any data to send to the API as a Python dict:
  6. “`python
    data = {
    ‘name’: ‘Phone’,
    ‘price’: 700
    }
    “`

  7. Make the POST request, passing the data:
  8. “`python
    response = requests.post(url, data=data)
    “`

    This will send a POST request to the specified URL, with the data dictionary serialized as JSON in the request body.

  9. Access data from the response:
  10. “`python
    print(response.status_code)
    print(response.json()[‘id’])
    “`

    Here we print the response status code and the id of the created resource.

The full Python script would be:

“`python
import requests

url = ‘https://api.example.com/items’

data = {
‘name’: ‘Phone’,
‘price’: 700
}

response = requests.post(url, data=data)

print(response.status_code)
print(response.json()[‘id’])
“`

This allows us to make a POST request to create a new resource in the API.

Authentication

Many APIs require authentication in order to access endpoints. There are several ways to handle authentication in Python requests:

API Key

Some APIs use API keys for authentication. You can pass the API key in the request headers:

“`python
headers = {
‘Authorization’: ‘Bearer YOUR_API_KEY’
}

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

Basic Auth

For basic authentication, you can pass the username and password in a tuple:

“`python
requests.get(url, auth=(‘username’,’password’))
“`

OAuth

For OAuth authentication, you need to first get an access token and pass that in the request:

“`python
access_token = get_access_token()

headers = {
‘Authorization’: f’Bearer {access_token}’
}

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

So Python has great support for handling authentication when working with REST APIs.

Parameters

You can pass parameters in the query string for GET requests and in the request data for POST requests.

For GET requests, pass a params dict:

“`python
params = {
‘limit’: 100,
‘sort’: ‘name’
}

response = requests.get(url, params=params)
“`

For POST requests, pass data as before:

“`python
data = {
‘name’: ‘Phone’,
‘price’: 700
}

requests.post(url, data=data)
“`

This allows you to dynamically customize your requests.

Handling Responses

The requests module makes it easy to handle API responses in Python.

To get the status code of the response:

“`python
status_code = response.status_code
“`

To get the JSON data from the response body:

“`python
data = response.json()
“`

To get the raw text of the response:

“`python
text = response.text
“`

You can also check if the request was successful:

“`python
if response.status_code == 200:
# Success code
else:
# Error handling
“`

And raise exceptions for errors:

“`python
response.raise_for_status()
“`

This makes it easy to robustly handle responses when interacting with REST APIs.

Example: Working with GitHub’s API

Let’s look at a full example using GitHub’s API to see Python making GET and POST requests in action.

First we’ll import the requests module:

“`python
import requests
“`

Get a list of repositories for a user:

“`python
url = ‘https://api.github.com/users/testuser/repos’

response = requests.get(url)

repos = response.json()

for repo in repos:
print(repo[‘name’])
“`

This loops through and prints the name of each repository returned by the API.

Now let’s create a new repository:

“`python
url = ‘https://api.github.com/user/repos’

data = {
‘name’: ‘New Repo’
}

response = requests.post(url, data=data)

print(response.status_code)
“`

We get back the status code to confirm creation of the repository.

This shows how easy it is to integrate with a real world REST API with Python!

Libraries for REST APIs

There are several Python libraries that make working with REST APIs even easier:

Requests

Requests is the most popular library for making HTTP requests in Python. It handles authentication, parameters, headers, and more. We used it in the examples above.

HTTPie

HTTPie provides a simple command line interface for making HTTP requests. It makes it easy to test and debug APIs.

Postman

Postman has a Python SDK that allows you to make requests and integrate with the Postman collection runner.

Django Rest Framework

DRF makes it easy to build REST APIs in Python, handling serialization, authentication, throttling, and more.

So there are some great options for even more advanced API usage than the standard requests module.

Conclusion

To summarize, Python is great for accessing REST APIs:

  • The requests module provides an easy interface for making GET and POST requests.
  • Authentication can be handled with API keys, OAuth, etc.
  • Parameters can be passed for dynamic requests.
  • Responses can be parsed and handled robustly.
  • There are many libraries for more advanced API usage.

Python’s simple syntax, vast ecosystem, and support for web APIs make it a great choice for integrating with REST API services. Whether you want to use public APIs or build your own API backend, Python has you covered!