Python API Request Example (GET Request)
This beginner-friendly example shows how to make a simple GET request in Python, read the response, and handle basic problems.
If you want the fastest working version first, use this:
import requests
url = "https://api.github.com/users/octocat"
response = requests.get(url)
print(response.status_code)
print(response.json())
This example uses the requests package and prints:
- The HTTP status code
- The JSON response from the API
What this example does
This example is useful because it shows the basic pattern for working with APIs in Python.
It will:
- Send a simple GET request to a public API
- Use the
requestspackage - Print the HTTP status code
- Read JSON data from the response
- Keep the code small and easy to follow
What you need before running it
Before you run the code, make sure you have:
- Python installed on your computer
- The
requestspackage installed - An internet connection
- A public API URL that allows GET requests
Install requests
To install requests, run this in your terminal:
pip install requests
If that does not work, try:
python -m pip install requests
Make sure you install it in the same Python environment you are using to run your script.
You can check that requests is installed with:
python -c "import requests; print(requests.__version__)"
If Python says the module cannot be found, see how to fix ModuleNotFoundError or how to fix ImportError.
Basic GET request example
Here is a complete beginner-friendly example:
import requests
url = "https://api.github.com/users/octocat"
response = requests.get(url)
print("Status code:", response.status_code)
print("JSON data:", response.json())
How this code works
import requestsloads the packageurl = ...stores the API address in a variablerequests.get(url)sends a GET request to that URLresponse.status_codeshows the result of the requestresponse.json()converts the JSON response into Python data
Example output
The exact output may vary, but it will look something like this:
Status code: 200
JSON data: {'login': 'octocat', 'id': 583231, 'type': 'User', ...}
If you want a broader walkthrough, see how to make an API request in Python.
How to understand the response
When you send a request, the server sends back a response.
Here are the most important parts for beginners:
status_codetells you whether the request worked200usually means successresponse.textgives the raw response as plain textresponse.json()converts JSON into Python objects- JSON objects usually become Python dictionaries
Example:
import requests
url = "https://api.github.com/users/octocat"
response = requests.get(url)
print("Status code:", response.status_code)
print("Text response:")
print(response.text[:200]) # first 200 characters
data = response.json()
print("User login:", data["login"])
In this example:
response.textshows the raw contentdata = response.json()creates a Python dictionarydata["login"]gets one value from that dictionary
If you want more help reading API output, see how to handle API responses in Python and the Python JSON module overview.
Safer version with error handling
The first example works, but real programs should handle errors.
This version is safer for beginners:
import requests
url = "https://api.github.com/users/octocat"
try:
response = requests.get(url, timeout=10)
response.raise_for_status()
data = response.json()
print("Request worked")
print("Status code:", response.status_code)
print("Login:", data["login"])
except requests.exceptions.Timeout:
print("The request took too long and timed out.")
except requests.exceptions.ConnectionError:
print("Could not connect to the server.")
except requests.exceptions.HTTPError as error:
print("The server returned an HTTP error:", error)
except ValueError:
print("The response was not valid JSON.")
Why this version is better
timeout=10prevents the program from waiting foreverraise_for_status()turns bad HTTP responses into errorstry-exceptlets you show simple messages instead of crashing
This is a good next step after learning the basic example.
Common problems beginners hit
Here are some common causes when this example does not work:
- The
requestspackage is not installed - The API URL is incorrect
- The server returns text or HTML instead of JSON
- The request needs headers or authentication
- The network connection fails or times out
You may also run into these specific issues:
ModuleNotFoundErrorifrequestsis not installed- JSON decode errors if the API does not return JSON
404if the URL is wrong- Timeout errors if the server is slow
- Permission or authentication problems with private APIs
Helpful commands:
python -m pip install requests
python -c "import requests; print(requests.__version__)"
python -c "import requests; print(requests.get('https://api.github.com').status_code)"
If you are working with JSON strings directly, how json.loads() works can also help.
When to use this example
This example is a good fit when you want to:
- Test a public API
- Learn how Python works with web data
- Fetch JSON for scripts and small projects
- Start with GET requests before learning POST requests or authentication
After this, a good next step is learning how to send a POST request in Python.
FAQ
What is a GET request in Python?
A GET request asks a server for data. In Python, beginners often use requests.get() to do this.
Do I need the requests package?
For this example, yes. It is the easiest beginner-friendly way to send HTTP requests.
Why use response.json()?
Use it when the API sends JSON. It converts the response into Python data like dictionaries and lists.
What if the API does not return JSON?
Use response.text instead. Trying response.json() on non-JSON data can cause an error.
What status code means success?
200 usually means the request worked.