Rates TodayNIFTY25,670-0.83%SENSEX83,630.7-0.83%Gold 24K ₹11,320.24/g down186.46Silver ₹134.77/g down2.72
InsightforGeeks
PythonPart of the Python learning hub

Call an API in Python With requests and Handle Errors

insightforgeeks-editorial
2 Dec 2026
3 min read
Share:

Most useful programs talk to other services: weather, payments, maps, your own back end. In Python, the requests library makes calling a web API a few lines of code. This guide covers GET and POST requests, reading JSON, and the error handling that separates a script that works from one that survives real life.

Install requests

Create and activate a virtual environment, then install the library:

pip install requests

Make a GET request

import requests

response = requests.get("https://jsonplaceholder.typicode.com/posts/1", timeout=10)
print(response.status_code)   # 200
data = response.json()        # the JSON body as a dictionary
print(data["id"])             # 1
print(data["title"][:20])

response.status_code is the HTTP status: 200 means success, 404 not found, 500 a server error. response.json() turns the JSON body into a Python dictionary or list. The site above is a free practice API that returns fake data.

Always set a timeout

Without a timeout, requests can wait forever for a server that never answers, and your program hangs. The value is in seconds. Use one on every call.

Send query parameters

import requests

params = {"userId": 1}
response = requests.get("https://jsonplaceholder.typicode.com/posts", params=params, timeout=10)
print(response.url)           # https://jsonplaceholder.typicode.com/posts?userId=1
posts = response.json()
print(len(posts), "posts")

Pass params as a dictionary instead of building the address by hand; requests encodes special characters correctly.

Send data with POST

import requests

payload = {"title": "Hello", "body": "From Python", "userId": 1}
response = requests.post("https://jsonplaceholder.typicode.com/posts", json=payload, timeout=10)
print(response.status_code)   # 201 means created
print(response.json()["title"])  # Hello

Using json=payload converts the dictionary to JSON and sets the Content-Type header for you. For a form post, use data=payload instead.

Headers and API keys

headers = {"Authorization": "Bearer YOUR_TOKEN", "Accept": "application/json"}
# requests.get(url, headers=headers, timeout=10)

Keep real keys out of your code. Read them from an environment variable with os.environ["API_KEY"] so they are never committed to Git.

Handle errors properly

A request can fail in two ways: the network breaks (no connection, timeout), or the server replies with an error status. raise_for_status() turns an error status into an exception, and RequestException covers everything requests can raise:

import requests

def get_post(post_id):
    url = f"https://jsonplaceholder.typicode.com/posts/{post_id}"
    try:
        response = requests.get(url, timeout=10)
        response.raise_for_status()
        return response.json()
    except requests.exceptions.Timeout:
        print("The server took too long to answer")
    except requests.exceptions.HTTPError as err:
        print("The server returned an error:", err)
    except requests.exceptions.RequestException as err:
        print("Request failed:", err)
    return None

print(get_post(1)["id"])   # 1
print(get_post(99999))     # prints an error message, then None

Catching the specific errors first, and the general one last, lets you show a clear message for each case instead of a long traceback.

Reuse connections with a Session

When you make several calls to the same server, a Session reuses the connection, which is faster, and lets you set headers once:

import requests

with requests.Session() as session:
    session.headers.update({"Accept": "application/json"})
    for post_id in (1, 2, 3):
        r = session.get(f"https://jsonplaceholder.typicode.com/posts/{post_id}", timeout=10)
        print(post_id, r.status_code)

Checklist for every API call

  • Set a timeout.
  • Call raise_for_status() or check status_code.
  • Wrap the call in try/except for requests.exceptions.RequestException.
  • Keep secrets in environment variables.
  • Respect the API's rate limits and terms.

Want to try an endpoint without writing code first? Use our API request tester, and paste the response into the JSON formatter to read it. To save what you fetch, see reading and writing files.

Tags:#python#requests#api#http#json
Found this helpful? Share it with friends & colleagues
Share:
insightforgeeks-editorial Verified Editorial Staff

Covering financial markets, commodity rates, and practical technology insights for India. Researched and fact-checked in accordance with our Editorial Policy.

Published on 2 December 2026General Information · Disclaimer
More in Python