To use a web API in Python, install the requests library, call requests.get(url), check the status code, and read the data with response.json(), which turns the API’s JSON into Python dictionaries and lists. The same pattern works for weather, maps, payments, CRMs, and almost every modern web service.

APIs (application programming interfaces) are how programs talk to each other over the internet. Instead of copying data from a website by hand, you ask the service’s API and get clean, structured data back, usually as JSON. Pulling sales from an online store, sending a message to Slack, checking the weather, or syncing contacts between two systems all come down to a few HTTP requests.

This guide shows how to call APIs with Python’s most popular HTTP library, requests: reading data, sending data, using API keys safely, handling errors, and putting it all together. Every example was run, and the outputs shown are real.

Before You Start

You need Python installed (see How to Install Python and Run Your First Script) and a virtual environment with requests:

python -m pip install requests

The examples use free public test APIs, so you don’t need an account: JSONPlaceholder (fake users and posts for practice), Open-Meteo (real weather data, no key needed), and httpbin (shows you exactly what you sent).

How Web APIs Work

A web API is a set of URLs, called endpoints, that return data instead of web pages. You send an HTTP request and get a response:

MethodUsed toExample
GETRead dataGet a customer’s details
POSTCreate somethingAdd a new order
PUT / PATCHUpdate somethingChange an address
DELETEDelete somethingRemove a record

Every response includes a status code: 200 means OK, 201 means something was created, 404 means not found, 401 or 403 means you’re not allowed, 429 means you’ve sent too many requests, and 5xx means the server had a problem.

Your First GET Request

import requests

response = requests.get("https://jsonplaceholder.typicode.com/users/1", timeout=10)
print(response.status_code)
user = response.json()
print(user["name"])
print(user["email"])
print(user["address"]["city"])
200
Leanne Graham
[email protected]
Gwenborough

response.json() converts the JSON body into Python objects, here a dictionary. Nested data, like the address, is a dictionary inside a dictionary, so you reach it with two keys. Always pass a timeout (in seconds): without one, a request to a server that never answers can hang your program forever.

Query Parameters

Many endpoints accept options in the URL, like filters or page numbers. Pass them as a dictionary with params and requests builds the URL for you:

import requests

response = requests.get(
    "https://jsonplaceholder.typicode.com/posts",
    params={"userId": 1},
    timeout=10,
)
posts = response.json()
print(response.url)
print(len(posts), "posts")
print(posts[0]["title"])
https://jsonplaceholder.typicode.com/posts?userId=1
10 posts
sunt aut facere repellat provident occaecati excepturi optio reprehenderit

response.url shows the final URL. Letting requests build it also takes care of encoding spaces and special characters.

Checking for Errors

A request that reaches the server succeeds even if the server says “no.” Check the status:

import requests

response = requests.get("https://jsonplaceholder.typicode.com/users/999", timeout=10)
print(response.status_code)
print(response.ok)
404
False

response.ok is True for any status below 400. In most scripts, it’s simpler to call raise_for_status(), which raises an error for 4xx and 5xx responses so your code can’t accidentally use bad data:

import requests

try:
    response = requests.get("https://jsonplaceholder.typicode.com/users/999", timeout=10)
    response.raise_for_status()
except requests.exceptions.HTTPError as error:
    print(f"Request failed: {error}")
Request failed: 404 Client Error: Not Found for url: https://jsonplaceholder.typicode.com/users/999

Sending Data With POST

To create something, send JSON with json=. requests converts the dictionary to JSON and sets the right Content-Type header:

import requests

new_post = {"title": "Server maintenance", "body": "Saturday at 10 p.m.", "userId": 1}
response = requests.post("https://jsonplaceholder.typicode.com/posts", json=new_post, timeout=10)
print(response.status_code)
print(response.json())
201
{'title': 'Server maintenance', 'body': 'Saturday at 10 p.m.', 'userId': 1, 'id': 101}

Status 201 means “created,” and the API returns the new record with its ID. (JSONPlaceholder only pretends to save it, which makes it safe for practice.)

API Keys and Headers

Most real APIs require a key or token so they know who’s calling. It usually goes in a header. Never type a key directly into your code, where it can end up in Git or a screenshot. Read it from an environment variable instead:

import os
import requests

os.environ["EXAMPLE_API_TOKEN"] = "demo-token-123"  # for this demo only

token = os.environ["EXAMPLE_API_TOKEN"]
headers = {"Authorization": f"Bearer {token}", "Accept": "application/json"}
response = requests.get("https://httpbin.org/headers", headers=headers, timeout=10)
print(response.json()["headers"]["Authorization"])
Bearer demo-token-123

httpbin echoes back the headers it received, which is handy for checking what you sent. In a real project, set the variable outside your code, or keep it in a .env file loaded with python-dotenv, as explained in The Importance of the .env File in Python Projects. Some APIs take the key as a query parameter instead; their documentation tells you which.

Handling Network Errors

Networks fail: servers go down, Wi-Fi drops, responses take too long. requests raises specific exceptions for each case, so you can handle them with try/except (covered in Python Basics: Files and Exceptions):

import requests

def get_json(url):
    """Return the JSON from url, or None if anything goes wrong."""
    try:
        response = requests.get(url, timeout=5)
        response.raise_for_status()
        return response.json()
    except requests.exceptions.Timeout:
        print("The server took too long to answer.")
    except requests.exceptions.ConnectionError:
        print("Could not connect. Check the address and your internet connection.")
    except requests.exceptions.HTTPError as error:
        print(f"The server returned an error: {error.response.status_code}")
    except requests.exceptions.JSONDecodeError:
        print("The response wasn't valid JSON.")
    return None

print(get_json("https://jsonplaceholder.typicode.com/users/999"))
print(get_json("https://this-domain-does-not-exist.example"))
The server returned an error: 404
None
Could not connect. Check the address and your internet connection.
None

Your program reports the problem and keeps running instead of crashing with a long traceback.

Pagination: Getting All the Results

APIs rarely return thousands of records at once. They split results into pages, and you request one page at a time until there are no more:

import requests

all_posts = []
page = 1
while True:
    response = requests.get(
        "https://jsonplaceholder.typicode.com/posts",
        params={"_page": page, "_limit": 25},
        timeout=10,
    )
    response.raise_for_status()
    batch = response.json()
    if not batch:
        break
    all_posts.extend(batch)
    page += 1

print(f"Downloaded {len(all_posts)} posts in {page - 1} pages")
Downloaded 100 posts in 4 pages

The parameter names vary by API (page, per_page, offset, cursor, or a “next” link in the response), so check the documentation. The loop pattern is the same.

Sessions and Automatic Retries

When you make many requests to the same API, use a session. It reuses the connection (faster), keeps headers for every request, and can retry automatically when the server is busy:

import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry

session = requests.Session()
retries = Retry(total=3, backoff_factor=1, status_forcelist=[429, 500, 502, 503, 504])
session.mount("https://", HTTPAdapter(max_retries=retries))
session.headers.update({"User-Agent": "inventory-report/1.0"})

for user_id in (1, 2, 3):
    user = session.get(f"https://jsonplaceholder.typicode.com/users/{user_id}", timeout=10).json()
    print(user["id"], user["name"], user["company"]["name"])
1 Leanne Graham Romaguera-Crona
2 Ervin Howell Deckow-Crist
3 Clementine Bauch Romaguera-Jacobson

Retry waits longer between each attempt (backoff_factor) and only retries the status codes you list, like 429 (too many requests) and temporary server errors. A clear User-Agent tells the API owner who’s calling, which some APIs require.

A Real Example: Current Weather

Open-Meteo provides real weather data with no sign-up. Here’s the current temperature in El Centro, California:

import requests

response = requests.get(
    "https://api.open-meteo.com/v1/forecast",
    params={
        "latitude": 32.79,
        "longitude": -115.56,
        "current": "temperature_2m,wind_speed_10m",
        "temperature_unit": "fahrenheit",
        "timezone": "America/Los_Angeles",
    },
    timeout=10,
)
response.raise_for_status()
current = response.json()["current"]
print(f"El Centro, CA at {current['time']}: {current['temperature_2m']}°F, wind {current['wind_speed_10m']} km/h")
El Centro, CA at 2026-11-30T19:00: 67.8°F, wind 6.6 km/h

Your numbers will differ, of course: it’s live data. Change the latitude and longitude for your own city.

Saving API Data to a CSV File

Once you have the data, saving it is plain Python. This writes every user to a CSV file you can open in Excel:

import csv
import requests

users = requests.get("https://jsonplaceholder.typicode.com/users", timeout=10).json()

with open("users.csv", "w", newline="", encoding="utf-8") as f:
    writer = csv.writer(f)
    writer.writerow(["id", "name", "email", "city"])
    for user in users:
        writer.writerow([user["id"], user["name"], user["email"], user["address"]["city"]])

print(f"Saved {len(users)} users to users.csv")
Saved 10 users to users.csv

For bigger jobs, load the data into pandas with pandas.DataFrame(users) and clean or analyze it there.

Being a Good API Citizen

  • Read the documentation and terms. They list the endpoints, limits, and what you’re allowed to do with the data.
  • Respect rate limits. If you get 429, slow down. Add time.sleep() between requests in loops, and use retries with backoff.
  • Cache what doesn’t change. Don’t download the same data every minute.
  • Keep keys secret. Use environment variables, never commit them, and rotate a key if it leaks.
  • Prefer an official API over scraping. When a site has an API, it’s more reliable than web scraping and usually what the owner wants you to use.

Common Mistakes to Avoid

  • No timeout. Always pass timeout=.
  • Not checking the status. Use raise_for_status() before reading the data.
  • Hard-coding API keys. Read them from environment variables.
  • Using data= instead of json= for JSON APIs. data= sends form data, which many JSON APIs reject.
  • Assuming every field exists. Use user.get("phone") when a field might be missing, so a missing key doesn’t crash the script.
  • Ignoring pagination. If you only get 25 or 100 results, there are probably more pages.

Frequently Asked Questions

What is the requests library?

requests is the most popular Python library for making HTTP requests. It isn’t part of the standard library, so you install it with pip. Python’s built-in urllib can do the same job, but with more code.

What’s the difference between requests and httpx?

httpx has an almost identical interface and adds support for asynchronous code and HTTP/2. For scripts and most beginner projects, requests is simpler; httpx is a good next step for async applications.

How do I find an API’s endpoints?

In its documentation, usually under “API reference” or “Developers.” Many APIs also publish an OpenAPI (Swagger) page where you can try requests in the browser.

Public APIs come with terms of use. Follow them, respect rate limits, and only use data the way the provider allows.

Conclusion

Working with APIs in Python comes down to one pattern: send a request with requests.get() or requests.post(), always with a timeout, check the response with raise_for_status(), and turn the JSON into Python data with .json(). Add query parameters with params=, send data with json=, keep keys in environment variables, handle network errors, loop through pages, and use a session with retries for bigger jobs. With those habits, almost any web service becomes something your scripts can automate. To build an API of your own, see FastAPI: Build a REST API in Python.