Make a GET request

import requests

response = requests.get("https://api.github.com")
print(response.status_code)   # 200
print(response.json())        # parsed JSON as a dict

requests.get fetches the URL, and response.json() parses a JSON body straight into a Python dictionary.

Send a POST request with data

import requests

payload = {"name": "Sam", "role": "developer"}
response = requests.post("https://httpbin.org/post", json=payload)
print(response.json())

Passing json=payload serialises your dictionary and sets the correct content-type header automatically.

Use urllib with no install

from urllib.request import urlopen

with urlopen("https://api.github.com") as response:
    body = response.read().decode("utf-8")
print(body[:60])

If you cannot install packages, the standard-library urllib works, though it is more verbose than requests.

Which method should you use?

  • requests.get / post — the everyday choice for clean, readable code.
  • response.json() — when the API returns JSON.
  • urllib — when you must avoid third-party packages.
  • Common mistake: not checking response.status_code or calling response.raise_for_status() before using the data.

Frequently asked questions

How do I add a timeout?

Pass timeout in seconds: requests.get(url, timeout=5). Without it, a slow server can hang your program indefinitely.

How do I send headers or an API key?

Pass a dictionary: requests.get(url, headers={"Authorization": "Bearer TOKEN"}).

Ready to build real programs that talk to APIs? Start with our free Python course.