Skip to main content

Making a simple API with Requests

Making a Simple API with Requests

The Requests library is one of the most popular libraries in Python for making HTTP requests. It abstracts the complexities of making requests behind a beautiful, simple API so that you can focus on interacting with services and consuming data in your application.

Getting Started

Before we start, you'll need to have Python installed on your computer. If you haven't installed it yet, you can download it from the official Python website.

Next, you'll need to install the Requests library. Open your terminal and type the following command:

pip install requests

Making a GET Request

The most common operation with the Requests library is the GET request. Let's try to send a GET request to a public API. For this tutorial, we'll use the JSONPlaceholder API.

import requests

response = requests.get('https://jsonplaceholder.typicode.com/posts')

print(response.status_code)
print(response.json())

In the above code, we first import the requests module and then use its get function to send a GET request to the specified URL. The function returns a Response object which contains the server's response to our request.

Understanding the Response

The response object contains a lot of information about the response we've received. Here are a few important ones:

  • status_code: This returns the HTTP status code that the server sent back. A status code of 200 means our request was successful. Other status codes indicate different types of errors.

  • json(): This method returns the JSON response body, which is often used when dealing with APIs.

Making a POST Request

In addition to GET requests, the Requests library also allows you to send POST requests, which are used to send data to the server. Here's a simple example:

import requests

data = {
"title": "foo",
"body": "bar",
"userId": 1
}

response = requests.post('https://jsonplaceholder.typicode.com/posts', json=data)

print(response.status_code)
print(response.json())

Handling Errors

It's important to handle potential errors in your requests. The Requests library provides a raise_for_status method that will throw an exception if the request was unsuccessful:

import requests

response = requests.get('https://jsonplaceholder.typicode.com/posts')

response.raise_for_status()

print(response.json())

In the above code, if the server returns an error status code, the raise_for_status method will raise a HTTPError exception. If there's no error, it won't do anything.

Conclusion

That's it for this tutorial! You should now have a basic understanding of how to make HTTP requests with the Requests library in Python. There's a lot more you can do with this library, such as sending headers or cookies with your requests, handling timeouts, and more. Be sure to check out the official documentation for more information.