How to Make an API Request in Python

If you want to get data from a website or service in Python, a common first step is making an API request.

This page shows the simplest way to send a basic GET request in Python, check whether it worked, and read JSON data safely. It stays focused on one task so you can get a working example quickly.

Quick example

Use this when you want the fastest working example.

You may need to install requests first:

pip install requests
import requests

url = "https://api.github.com"
response = requests.get(url)

print(response.status_code)
print(response.json())

What this does:

  • Sends a GET request to https://api.github.com
  • Stores the server's reply in response
  • Prints the HTTP status code
  • Parses the JSON response into Python data

What this page helps you do

This page is about one specific task: sending a basic API request in Python.

It focuses on:

  • Making a GET request
  • Understanding the response
  • Reading JSON data
  • Doing a few basic error checks

In simple terms, an API is a way for one program to ask another program for data.


What you need first

Before you start, make sure you have:

  • Python installed
  • An internet connection
  • The requests package installed
  • A test API URL that returns JSON

For the examples below, we will use:

url = "https://api.github.com"

Install the requests package

requests is a popular Python library for sending HTTP requests. It is much easier for beginners than using lower-level tools.

Install it with:

pip install requests

If that does not work, your pip command may be connected to a different Python version than the one you are running.

These commands can help you check:

python --version
pip --version
python -c "import requests; print(requests.__version__)"

If Python says the package is missing, see how to fix ModuleNotFoundError: No module named x.


Make your first GET request

A GET request asks a server for data.

Here is a simple example:

import requests

url = "https://api.github.com"
response = requests.get(url)

print(response.status_code)

How it works

  • requests.get(url) sends the request
  • The result is stored in response
  • response.status_code shows the HTTP status code

A status code of 200 usually means the request worked.

Example output:

200

If you want a slightly safer version, use:

import requests

url = "https://api.github.com"
response = requests.get(url)
response.raise_for_status()

print("Request worked")

response.raise_for_status() raises an error if the server returned a bad status, such as 404 or 500.


Read JSON data from the response

Many APIs return data in JSON format.

In Python, you can parse that JSON with response.json():

import requests

url = "https://api.github.com"
response = requests.get(url)
response.raise_for_status()

data = response.json()

print(data)
print(data["current_user_url"])

What response.json() returns

JSON becomes normal Python objects such as:

  • Dictionaries
  • Lists
  • Strings
  • Numbers
  • Booleans

In the example above, data is a Python dictionary, so you can access values by key.

If you want to learn more about JSON in Python, see the Python JSON module overview or json.loads() explained.


Check for errors before using the data

Even if your Python code is correct, the request can still fail.

For example:

  • The server may be down
  • The URL may be wrong
  • The request may time out
  • The server may return an error page instead of JSON

A good beginner pattern is:

import requests

url = "https://api.github.com"

response = requests.get(url)

if response.status_code == 200:
    data = response.json()
    print(data)
else:
    print("Request failed with status code:", response.status_code)

Another simple option is to use raise_for_status():

import requests

url = "https://api.github.com"

try:
    response = requests.get(url)
    response.raise_for_status()
    data = response.json()
    print(data)
except requests.exceptions.RequestException as error:
    print("Request failed:", error)

This is useful because it catches common request-related problems in one place.

For the next step after making a request, see how to handle API responses in Python.


Add query parameters

Some APIs need extra values in the URL, such as search terms, page numbers, or filters.

Use the params argument instead of building the query string by hand.

import requests

url = "https://httpbin.org/get"
params = {
    "search": "python",
    "page": 1
}

response = requests.get(url, params=params)
response.raise_for_status()

print(response.url)
print(response.json())

Why params is better

  • Your code is easier to read
  • requests builds the final URL for you
  • It handles URL encoding automatically

For example, requests will create a URL like this:

https://httpbin.org/get?search=python&page=1

Handle common request problems

Here are some common problems beginners run into.

Connection problems

If your internet connection is down, or the server is unavailable, the request can fail.

import requests

try:
    response = requests.get("https://api.github.com")
    response.raise_for_status()
except requests.exceptions.ConnectionError:
    print("Could not connect to the server")

Timeouts

Sometimes a server is too slow to respond.

You can set a timeout so your program does not wait forever:

import requests

try:
    response = requests.get("https://api.github.com", timeout=5)
    response.raise_for_status()
    print(response.json())
except requests.exceptions.Timeout:
    print("The request took too long")

Invalid URL

If the URL is malformed, requests can raise an error.

import requests

try:
    response = requests.get("not-a-real-url")
except requests.exceptions.RequestException as error:
    print("Request error:", error)

Non-JSON response

Not every server returns JSON. Some return plain text or HTML.

import requests

response = requests.get("https://example.com")
print(response.text)

If response.json() fails, check the raw text first:

import requests

try:
    response = requests.get("https://example.com")
    data = response.json()
except ValueError:
    print("The response was not valid JSON")
    print(response.text)

Missing requests package

If Python shows an import error like this:

import requests
ModuleNotFoundError: No module named 'requests'

install the package with:

pip install requests

If the problem continues, see how to fix ModuleNotFoundError: No module named x.


Beginner tips for understanding the response

When you get a response object, these parts are the most useful:

  • response.status_code
    Shows the HTTP result, such as 200 or 404
  • response.text
    Gives the raw response body as a string
  • response.json()
    Parses JSON into Python objects
  • response.headers
    Contains metadata about the response

Example:

import requests

response = requests.get("https://api.github.com")

print("Status code:", response.status_code)
print("Headers:", response.headers)
print("Text:", response.text[:100])

This is a good way to inspect a response when you are not sure what the API returned.


Common mistakes

These are some common causes of problems when making an API request in Python:

  • The requests package is not installed
  • The API URL is wrong
  • The API requires parameters or authentication
  • The server returns text or HTML instead of JSON
  • The request times out because the server is slow
  • No internet connection or DNS issue

Useful commands for debugging:

pip install requests
python --version
pip --version
python -c "import requests; print(requests.__version__)"

FAQ

Do I need the requests library to make an API request in Python?

No, but it is the easiest option for beginners. Python also has urllib, but requests is simpler to read and use.

What does response.status_code mean?

It is the HTTP status code from the server. For example, 200 usually means success and 404 usually means not found.

Why does response.json() fail?

It usually fails when the server did not return valid JSON. Check response.text and the status code first.

Can I use this for APIs that need a key?

Yes, but that is better covered on a separate page about authentication or headers so this page stays focused.


See also