Skip to lesson content

API & Data · Lesson 15 of 17

Python HTTP Requests Using `requests` Library

Introduction

Fetch, send, update and delete data with examples you can run in Python.

Installing the Requests Library

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

pip install requests

Once installed, you can import it into your Python code:

import requests

Examples of Basic HTTP Requests

Here are some examples to showcase how different types of HTTP requests can be made using requests:

1. Making a GET Request

Retrieve data from a server using the GET method:

import requests

# Simple GET request
response = requests.get("https://jsonplaceholder.typicode.com/posts")

# Print the response
if response.status_code == 200:
    print(response.json())
else:
    print(f"Error: {response.status_code}")

View source on GitHub

2. Making a POST Request

Send data to a server (e.g., submitting a form):

import requests

# Data to send in the POST request
data = {
    "title": "foo",
    "body": "bar",
    "userId": 1
}

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

# Print the response
if response.status_code == 201:
    print(response.json())
else:
    print(f"Error: {response.status_code}")

View source on GitHub

3. Making a PUT Request

Update an existing resource on a server:

import requests

# Data to update in the PUT request
data = {
    "id": 1,
    "title": "updated title",
    "body": "updated body",
    "userId": 1
}

response = requests.put("https://jsonplaceholder.typicode.com/posts/1", json=data)

# Print the response
if response.status_code == 200:
    print(response.json())
else:
    print(f"Error: {response.status_code}")

View source on GitHub

4. Making a DELETE Request

Delete a resource from a server:

import requests

response = requests.delete("https://jsonplaceholder.typicode.com/posts/1")

# Print status code
if response.status_code == 200:
    print("Resource deleted successfully.")
else:
    print(f"Error: {response.status_code}")

View source on GitHub

Working with Request Headers

You can add custom headers to your HTTP requests using the headers parameter:

import requests

# Custom headers
headers = {
    "Authorization": "Bearer YOUR_API_TOKEN",
    "Content-Type": "application/json"
}

response = requests.get("https://jsonplaceholder.typicode.com/posts", headers=headers)

# Print the response
if response.status_code == 200:
    print(response.json())
else:
    print(f"Error: {response.status_code}")

View source on GitHub

Error Handling and Response Validation

Always check the status code to ensure a request was successful. In the example below:

  • The status_code of the response is checked to confirm if the request succeeded (200 OK).
  • If the response is successful (status_code == 200), the data is printed in JSON format.
  • If the request fails (e.g., other status codes like 404 or 500), the failure status code is displayed.

This provides a simple way to validate and handle HTTP responses effectively.

import requests

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

if response.status_code == 200:
    print(f"Request successful! Status code: {response.status_code}")
    print(response.json())
else:
    print(f"Request failed with status code: {response.status_code}")

View source on GitHub

Summary

With the requests library, you can efficiently make HTTP requests in Python. It simplifies interaction with web servers, allowing you to easily handle GET, POST, PUT, DELETE, and other HTTP methods.