Python REST API Requests

REST APIs (Representational State Transfer) are widely used for enabling communication between systems over the internet. Python provides an easy-to-use library called requests for making HTTP requests. In this tutorial, we will cover how to make GET, POST, PUT, and DELETE requests to a REST API using Python.

1. Installing the Requests Library

The requests library is not included with Python by default, so you need to install it. You can install it using pip.

pip install requests

Try It Now

2. Making a GET Request

A GET request is used to retrieve data from an API. Here’s how to make a simple GET request to an API:

Example of a GET Request:

import requests

# Make a GET request to a public API
response = requests.get("https://jsonplaceholder.typicode.com/posts")

# Check if the request was successful
if response.status_code == 200:
    data = response.json()  # Parse JSON response
    print(data)
else:
    print(f"Failed to retrieve data: {response.status_code}")

Try It Now

3. Making a POST Request

A POST request is used to send data to an API, such as submitting a form. Here’s how to send a POST request with data:

Example of a POST Request:

import requests

# Define the data to be sent to the API
data = {"title": "New Post", "body": "This is the content of the post", "userId": 1}

# Make a POST request to create a new post
response = requests.post("https://jsonplaceholder.typicode.com/posts", json=data)

# Check if the request was successful
if response.status_code == 201:
    print("Post created successfully!")
    print(response.json())  # Print the response data
else:
    print(f"Failed to create post: {response.status_code}")

Try It Now

4. Making a PUT Request

A PUT request is used to update data on the server. It is commonly used for updating existing resources.

Example of a PUT Request:

import requests

# Define the updated data
updated_data = {"id": 1, "title": "Updated Post", "body": "This is the updated content", "userId": 1}

# Make a PUT request to update the post
response = requests.put("https://jsonplaceholder.typicode.com/posts/1", json=updated_data)

# Check if the request was successful
if response.status_code == 200:
    print("Post updated successfully!")
    print(response.json())  # Print the updated data
else:
    print(f"Failed to update post: {response.status_code}")

Try It Now

5. Making a DELETE Request

A DELETE request is used to remove data from the server. Here’s how to delete a resource from an API:

Example of a DELETE Request:

import requests

# Make a DELETE request to remove a post
response = requests.delete("https://jsonplaceholder.typicode.com/posts/1")

# Check if the request was successful
if response.status_code == 200:
    print("Post deleted successfully!")
else:
    print(f"Failed to delete post: {response.status_code}")

Try It Now

6. Handling Response Status Codes

When making requests to an API, the server will return a status code. It’s important to handle different status codes appropriately to ensure your program runs smoothly.

Common HTTP Status Codes:

  • 200 OK – The request was successful.
  • 201 Created – The request was successful and a resource was created.
  • 400 Bad Request – The request was invalid.
  • 401 Unauthorized – Authentication is required.
  • 404 Not Found – The requested resource was not found.
  • 500 Internal Server Error – The server encountered an error.

7. Sending Headers with Requests

Sometimes you may need to send custom headers along with your requests, such as for authentication or content type. You can do this by passing a headers parameter to the request.

Example of Sending Headers:

import requests

# Define custom headers (e.g., for authentication)
headers = {"Authorization": "Bearer your_token"}

# Make a GET request with custom headers
response = requests.get("https://jsonplaceholder.typicode.com/posts", headers=headers)

# Check if the request was successful
if response.status_code == 200:
    print(response.json())
else:
    print(f"Failed to retrieve data: {response.status_code}")

Try It Now

8. Handling JSON Responses

Most modern REST APIs return data in JSON format. You can parse the response and work with it as a Python dictionary using the .json() method.

Example of Handling JSON Responses:

import requests

# Make a GET request to a public API
response = requests.get("https://jsonplaceholder.typicode.com/posts")

# Parse the JSON response
data = response.json()

# Iterate over the response data
for post in data:
    print(f"Post ID: {post['id']}, Title: {post['title']}")

Try It Now

9. Timeout and Error Handling

It’s important to handle timeouts and potential errors when working with APIs to ensure your application doesn’t crash unexpectedly.

Example of Timeout Handling:

import requests

try:
    # Set a timeout of 5 seconds
    response = requests.get("https://jsonplaceholder.typicode.com/posts", timeout=5)
    response.raise_for_status()  # Raise an exception for bad responses (4xx, 5xx)
    print(response.json())
except requests.exceptions.Timeout:
    print("The request timed out!")
except requests.exceptions.RequestException as e:
    print(f"An error occurred: {e}")

Try It Now

Conclusion

Python’s requests library makes it easy to interact with REST APIs. In this tutorial, we covered how to make GET, POST, PUT, and DELETE requests, handle responses, send headers, and manage errors.