Last modified: Jan 30, 2026 By Alexander Williams

Python API Calls 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. Its simplicity and powerful libraries make it ideal.

This guide will teach you how to make API calls in Python. You will learn the core concepts. We will cover making requests and handling responses. You will also learn about common errors and best practices.

By the end, you will be confident in fetching data from the web. You can use this skill for data analysis, automation, and building apps.

What is an API Call?

An API call is a request sent from one software application to another. It asks for data or an action. The receiving application processes the request and sends back a response.

Think of it like a waiter in a restaurant. You (the client) give an order (the request). The waiter takes it to the kitchen (the server). The kitchen prepares the food and the waiter brings it back (the response).

In web development, this happens over HTTP or HTTPS protocols. Python can act as the client, sending these requests effortlessly.

Setting Up: Install the Requests Library

Python has a built-in module called urllib. But the requests library is much easier to use. It is the standard for making HTTP requests in Python.

First, you need to install it. Open your terminal or command prompt. Run the following command.


pip install requests

Once installed, you can import it into your Python script. Now you are ready to start making calls.

Making Your First GET Request

The most common API call is a GET request. It fetches data from a server. Let's use a free public API for our example. We will get a random joke from the Official Joke API.


import requests

# Define the API endpoint URL
url = "https://official-joke-api.appspot.com/random_joke"

# Send a GET request to the URL
response = requests.get(url)

# Check if the request was successful (status code 200)
if response.status_code == 200:
    # Parse the JSON data from the response
    joke_data = response.json()
    print(f"Setup: {joke_data['setup']}")
    print(f"Punchline: {joke_data['punchline']}")
else:
    print(f"Error: Failed to retrieve data. Status Code: {response.status_code}")

Let's break down the code. We import the requests module. We define the API URL. We use the requests.get() function to send the request.

The server's reply is stored in the response object. We check its status_code. A code of 200 means success. We then use response.json() to convert the data from JSON format into a Python dictionary.


Setup: Why did the scarecrow win an award?
Punchline: He was outstanding in his field.

Your output will be a different random joke. This simple example shows the basic flow of an API call.

Understanding HTTP Status Codes

The status code tells you the result of your request. It is a crucial part of the response. You must always check it.

Common status codes include:

  • 200 OK: The request succeeded.
  • 201 Created: A new resource was created.
  • 400 Bad Request: The server could not understand the request.
  • 401 Unauthorized: Authentication is needed.
  • 404 Not Found: The requested resource does not exist.
  • 500 Internal Server Error: The server encountered an error.

Handling these codes properly makes your application robust. For a deeper dive into managing different data types, see our Python API Number Handling Guide.

Sending Data with POST Requests

Not all APIs are just for getting data. Some require you to send data to create or update resources. This is done with a POST request.

Let's simulate a POST request to a test API. We will send some sample user data.


import requests
import json

# Test API endpoint for posting data
url = "https://jsonplaceholder.typicode.com/posts"

# Data to send (usually as a dictionary)
data_to_send = {
    "title": "My Python API Post",
    "body": "This is the content of the post sent from Python.",
    "userId": 1
}

# Headers tell the server what kind of data we are sending
headers = {
    "Content-type": "application/json; charset=UTF-8"
}

# Send a POST request with the data
response = requests.post(url, json=data_to_send, headers=headers)

# Check the response
print(f"Status Code: {response.status_code}")
if response.status_code == 201:
    returned_data = response.json()
    print("Server Response:")
    print(json.dumps(returned_data, indent=2))

We use requests.post() instead of get. We pass the data as the json parameter. The headers dictionary informs the server we are sending JSON.


Status Code: 201
Server Response:
{
  "title": "My Python API Post",
  "body": "This is the content of the post sent from Python.",
  "userId": 1,
  "id": 101
}

The server responds with a 201 Created status. It echoes back our data with a new id field. This pattern is common when creating new items in a database.

Handling Errors and Exceptions

Networks are unreliable. Servers can be down. APIs change. Your code must handle failures gracefully. Use try-except blocks.


import requests
from requests.exceptions import RequestException

url = "https://api.example.com/data"

try:
    response = requests.get(url, timeout=5) # Timeout after 5 seconds
    response.raise_for_status() # Raises an HTTPError for bad status codes (4xx or 5xx)
    data = response.json()
    print("Data fetched successfully.")
except requests.exceptions.Timeout:
    print("Error: The request timed out. The server is too slow.")
except requests.exceptions.ConnectionError:
    print("Error: Failed to connect to the server. Check your network.")
except requests.exceptions.HTTPError as http_err:
    print(f"Error: HTTP error occurred: {http_err}")
except RequestException as err:
    print(f"Error: An unexpected request error occurred: {err}")
except ValueError as json_err:
    print(f"Error: Failed to decode JSON response: {json_err}")

The timeout parameter prevents your program from hanging. The raise_for_status() method is a shortcut. It checks if the status code indicates an error and raises an exception.

This structure ensures your script can inform the user of the problem. It can then exit cleanly or retry the operation.

Working with Query Parameters and Headers

Many APIs require extra information. This is often passed as query parameters in the URL or as headers.

Query Parameters filter or customize a request. For example, searching for a specific user. You can pass them as a dictionary to the params argument.


import requests

base_url = "https://jsonplaceholder.typicode.com/posts"
params = {
    "userId": 1
}

response = requests.get(base_url, params=params)
print