Skip to content
The App Code
How-to

Make a GET Request in Python

Fetch JSON from an API using the requests library, raising on error status codes.

Also known as: requests GET Python, Python HTTP request

beginner

Call requests.get(url), call raise_for_status() to turn 4xx/5xx into exceptions, then response.json() to parse the body.

What it is

The requests library is the most widely used HTTP client in Python for its readable API. requests.get(url, params=...) sends the request and returns a Response. Unlike JavaScript's fetch, it does not automatically raise on HTTP errors — but calling response.raise_for_status() will raise requests.HTTPError for any 4xx/5xx, which is the idiomatic way to fail fast.

Use the params argument to let requests URL-encode your query string safely, and set a timeout so a hung server can't block your program forever.

Worked example

import requests

def get_post(post_id: int) -> dict:
    url = f"https://jsonplaceholder.typicode.com/posts/{post_id}"
    response = requests.get(url, timeout=10)
    response.raise_for_status()  # raises on 4xx / 5xx
    return response.json()

if __name__ == "__main__":
    post = get_post(1)
    print(post["title"])

Failure mode — when it misleads

Omitting timeout is the classic bug: requests has no default timeout, so a slow or unresponsive server can hang your program indefinitely. Also, requests is not in the standard library — install it with pip install requests; for the stdlib-only option use urllib.request.

Sources & further reading