Last modified: Feb 01, 2026 By Alexander Williams

Python Requests API Guide for Beginners

APIs are the backbone of modern software. They let applications talk to each other. Python is a top choice for working with APIs. The requests library makes it simple.

This guide will teach you the essentials. You will learn how to send requests and handle data. We will cover installation, basic calls, and advanced features.

What is the Python Requests Library?

The requests library is a popular HTTP client for Python. It simplifies making web requests. You can fetch data from APIs and websites with ease.

It is known for being human-friendly. The syntax is clean and intuitive. It handles complexities like sessions and authentication for you.

For a broader look at connecting Python to various services, see our Python API Tutorial for Beginners.

Installing the Requests Library

First, you need to install it. Use the package manager pip. Run this command in your terminal.


pip install requests
    

That's it. You are ready to start making API calls.

Making Your First API Request

Let's start with a simple GET request. We will fetch data from a public API. This example uses JSONPlaceholder.


import requests

# Send a GET request to an API endpoint
response = requests.get('https://jsonplaceholder.typicode.com/posts/1')

# Check if the request was successful
if response.status_code == 200:
    print("Request successful!")
    # Parse the JSON response into a Python dictionary
    data = response.json()
    print(f"Post Title: {data['title']}")
else:
    print(f"Request failed with status code: {response.status_code}")
    

Request successful!
Post Title: sunt aut facere repellat provident occaecati excepturi optio reprehenderit
    

The requests.get() function sends the request. The response.json() method converts the JSON response to a Python dictionary. Always check the status code.

Understanding HTTP Methods

APIs use different HTTP methods. Each method has a specific purpose. Requests supports them all.

GET retrieves data from a server. It is the most common method.

POST sends data to a server to create a new resource.

PUT updates an existing resource on the server.

DELETE removes a resource from the server.

PATCH applies partial modifications to a resource.

Example: POST Request

Here is how to send data to an API.


import requests

# Data to send in the request body
new_post = {
    'title': 'My New Post',
    'body': 'This is the content of my post.',
    'userId': 1
}

# Send a POST request to create a new post
response = requests.post('https://jsonplaceholder.typicode.com/posts', json=new_post)

print(f"Status Code: {response.status_code}")
print(f"Response JSON: {response.json()}")
    

Status Code: 201
Response JSON: {'title': 'My New Post', 'body': 'This is the content of my post.', 'userId': 1, 'id': 101}
    

We used the json parameter. The library automatically sets the correct headers. A status code of 201 means "Created".

Working with Query Parameters and Headers

APIs often require extra information. You can send this via query parameters or headers.

Adding Query Parameters

Use the params argument in your request.


import requests

# Define query parameters
params = {
    'userId': 1
}

# The library will construct the URL: https://.../posts?userId=1
response = requests.get('https://jsonplaceholder.typicode.com/posts', params=params)

print(f"URL sent: {response.url}")
print(f"Number of posts: {len(response.json())}")
    

Setting Custom Headers

Some APIs need specific headers for authentication. Use the headers argument.


import requests

headers = {
    'Authorization': 'Bearer YOUR_ACCESS_TOKEN_HERE',
    'User-Agent': 'MyPythonApp/1.0'
}

response = requests.get('https://api.example.com/data', headers=headers)
    

This is crucial for services like the ChatGPT Python API which require an API key in the headers.

Handling Response Data and Errors

A good program handles both success and failure. The response object gives you tools for this.

Checking for Success

Use response.raise_for_status(). It raises an exception for bad status codes (4xx or 5xx).


import requests

try:
    response = requests.get('https://jsonplaceholder.typicode.com/invalid_endpoint')
    response.raise_for_status()  # Will raise HTTPError for 404
    data = response.json()
except requests.exceptions.HTTPError as err:
    print(f"HTTP error occurred: {err}")
except requests.exceptions.RequestException as err:
    print(f"An error occurred: {err}")
    

Accessing Response Content

You can access the raw response in different formats.

response.text returns the content as a string.

response.content returns the content as bytes.

response.json() parses JSON content into a dictionary/list.

Advanced Features: Sessions and Timeouts

For more control, use a Session object. It persists parameters across requests.


import requests

# Create a session
with requests.Session() as session:
    session.headers.update({'User-Agent': 'MySessionApp'})
    
    # All requests in this block use the same session
    resp1 = session.get('https://httpbin.org/get')
    resp2 = session.get('https://httpbin.org/cookies/set/sessioncookie/123456789')
    
    print(session.cookies.get_dict())
    

Always set a timeout. It prevents your program from hanging forever.


try:
    # Timeout after 5 seconds
    response = requests.get('https://httpbin.org/delay/10', timeout=5)
except requests.exceptions.Timeout:
    print("The request timed out!")
    

Common Use Cases and Examples

The Requests library is versatile. Here are some practical applications.

You can use it to pull data from financial APIs, as shown in our