Self-paced

Explore our extensive collection of courses designed to help you master various subjects and skills. Whether you're a beginner or an advanced learner, there's something here for everyone.

Bootcamp

Learn live

Join us for our free workshops, webinars, and other events to learn more about our programs and get started on your journey to becoming a developer.

Upcoming live events

Learning library

For all the self-taught geeks out there, here is our content library with most of the learning materials we have produced throughout the years.

It makes sense to start learning by reading and watching videos about fundamentals and how things work.

Search from all Lessons


LoginGet Started
← Back to How to's
  • HTTP

  • Python

    Flask

  • APIs

  • http requests

Edit on Github

How to consume an API in Python?

Written by:

How to Consume an API in Python using requests?
How to Consume an API?

How to Consume an API in Python using requests?

In the world of modern development, it's very common to use an API (Application Programming Interface) to connect to third-party services. For example, if you're creating an application where you need to track users' locations, instead of writing all the necessary code for that, you can simply use the Google Maps API.

In this article, we will see how to consume an API in Python with the help of the Requests library. In the following example, we will look at a simple case of a GET request to the free jsonplaceholder API

To use the Requests library, you first need to install it on your computer. You can do this with the following command:

1pip install requests

Once installed, you can use it in your code to make HTTP requests, in this case, a GET request for an example user.

1import requests 2 3URL = "https://jsonplaceholder.typicode.com/users/1" 4response = requests.get(URL) 5 6if response.status_code == 200: 7 print('Successful request') 8 print('Data:', response.json()) 9else: 10 print('Error in the request, details:', response.text)

Code output:

1successful request 2Data: { 3 "id": 1, 4 "name": "Leanne Graham", 5 "username": "Bret", 6 "email": "Sincere@april.biz", 7 "address": { 8 "street": "Kulas Light", 9 "suite": "Apt. 556", 10 "city": "Gwenborough", 11 "zipcode": "92998-3874", 12 "geo": { 13 "lat": "-37.3159", 14 "lng": "81.1496" 15 } 16 }, 17 "phone": "1-770-736-8031 x56442", 18 "website": "hildegard.org", 19 "company": { 20 "name": "Romaguera-Crona", 21 "catchPhrase": "Multi-layered client-server neural-net", 22 "bs": "harness real-time e-markets" 23 } 24}

In this example, we use the get(api_url) method of the requests library to retrieve information from a fake user provided by the jsonplaceholder API. This method returns the information received from the API and stores it in the response variable. If the request was successful, the API returns a status_code in the range of 2XX (between 200 and 299) and the user information. If there was an error in the process, it returns a status_code in the 4XX range (between 400 and 499) and a message explaining the error.

What is an API in Python?

APIs are mechanisms that allow two software components to communicate with each other through a set of definitions and protocols. In the context of programming, an API is used to access functions and data from an external application. In Python, APIs are a common way to obtain and manipulate data from online services such as web services, databases, and other external resources.

A common example of an API is the weather API, which provides basic information about the weather in any city or country. If you need to create an application that requires weather information from anywhere in the world, you can use this API via HTTP protocols to retrieve and use that information directly in your application

How to Consume an API?

Below are some examples of how to consume an API in Python using the Requests library and the free jsonplaceholder API that provides simulated data. To get started, you need to install the requests library on your computer with the following command:

1pip install requests

This library allows you to access information obtained from an API in a very simple way. Here are some of the most common methods and properties for accessing the information returned by requests:

PropertyDescription
response.status_codeContains the status code of the request, e.g., 201
response.urlContains the URL of the request.
response.headersProvides the headers of the request.
response.cookiesProvides the cookies of the request.
response.encodingContains the encoding of the request, e.g., utf-8.
response.json()Stores the information received from the API. For example, in the weather API, it might be a list of dictionaries with city information.

Important note: Requests to the jsonplaceholder API only simulate the behavior of a real API. Not all requests are functional. For example, if you make a POST request to the jsonplaceholder API, the information will NOT be saved on the API's servers, but the API responds with a message that simulates success.

Example with GET request

GET requests are used to retrieve information from a server.

1import requests 2 3URL = "https://jsonplaceholder.typicode.com/posts/1" 4response = requests.get(URL) 5 6if response.status_code == 200: 7 data = response.json() 8 9 print('Successful request') 10 print('Data:', data) 11else: 12 print('Error in the request, details:', response.text)

code output:

1successful request 2Data: { 3 'userId': 1, 4 'id': 1, 5 'title': 'sunt aut facere repellat provident occaecati excepturi optio reprehenderit', 6 'body': 'quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto' 7}

In this example, we use the get() method of the requests library to retrieve information about a simulated post from the jsonplaceholder API. This information is stored in the response variable. Then, with an if-else conditional, we check if the API request was successful. If it was, we print the information to the console; otherwise, we print an error message.

Example with POST request

POST requests are used to send data to the server.

1import requests 2 3URL = "https://jsonplaceholder.typicode.com/posts" 4DATA = { 5 "title": "Example Title", 6 "body": "Content of a new post", 7 "userId": 1 8} 9 10response = requests.post(URL, json=DATA) 11 12if response.status_code == 201: 13 data = response.json() 14 15 print('Post created successfully') 16 print('Response:', data) 17else: 18 print('Error in the request, details:', response.text)

Code output:

1Post created successfully 2Response: { 3 'title': 'Example Title', 4 'body': 'Content of a new post', 5 'userId': 1, 6 'id': 101 7}

In this example, we use the post() method from the requests library to create a new object on the server. post() method takes two parameters: the first one is the API URL, and the second one is the information of the object we want to create within a dictionary.

Example with PUT request

PUT requests are used to update data on the server.

1import requests 2 3URL = "https://jsonplaceholder.typicode.com/posts/1" 4DATA = { 5 "title": "Título actualizado", 6 "userId": 2 7} 8 9response = requests.put(URL, json=DATA) 10 11if response.status_code == 200: 12 data = response.json() 13 14 print('Post updated successfully') 15 print('Response:', data) 16else: 17 print('Error in the request, details:', response.text)

code output:

1Post updated successfully 2Response: { 3 'title': 'Updated Title', 4 'userId': 2, 5 'id': 1 6}

To make a PUT request, we need to use the put() method from the requests library. This method also takes two parameters: the first one is the URL that tells the API which specific object you want to update, and the second parameter is the information with which you want to update the object.

Example with DELETE request

DELETE requests are used to delete data on the server.

1import requests 2 3URL = "https://jsonplaceholder.typicode.com/posts/1" 4response = requests.delete(URL) 5 6if response.status_code == 200: 7 print('Post deleted successfully.') 8else: 9 print('Error in the request, details:', response.text)

code output:

1Post deleted successfully.

To make a DELETE request in Python, we need to use the delete() method from the requests library. This method takes the URL as a parameter, indicating which specific object you want to delete. Normally, APIs return a message indicating whether the object was deleted successfully or not, but the jsonplaceholder API does not return a specific message; it only returns a 200 status_code.

Conclusion

APIs play a fundamental role in application integration and data exchange in the world of software development. In Python, the Requests library allows us to interact with APIs in a simple and intuitive way. In this article, we learned how to use this library to make HTTP requests to obtain, create, update, or delete information in an API. Now, you are ready to consume an API correctly and use its functionalities in your own applications.

To dive deeper into consuming APIs with Python, we highly encourage you to take this interactive course. It's a great opportunity to learn hands-on and master the requests module:

👉 Take this interactive course on Python HTTP Requests & API!

Don't miss out! It's the first step toward becoming an expert in API integration.