Call an API in Python: 6 Simple Steps for Total Beginners
I still remember the first time I made an API call from Python. I was staring at a blank terminal, my hands hovering over the keyboard, and I had absolutely no idea what I was doing. The tutorial I was following said something like "just use requests.get()" — as if that was obvious. It wasn't. But after about twenty minutes of trial and error (and one very helpful error message), I saw a wall of JSON data appear on my screen. It felt like magic. And honestly? It's not that hard once you break it down. Here are six simple steps to call an API from Python, even if you've never done it before.
What Is an API and Why Would a Beginner Call One from Python?
An API — or Application Programming Interface — is basically a waiter at a restaurant. You tell the waiter what you want (the request), they go to the kitchen (the server), and then they bring back your order (the response). In the digital world, an API lets your Python script ask another program for data. Maybe you want today's weather, a random joke, or the latest news headlines. Instead of scraping a messy webpage, you send a clean request and get clean data back.
For a beginner, calling an API is one of the fastest ways to get real-world data into your code. No need to build a database or write complex scraping logic. You just need Python, an internet connection, and a few lines of code. The payoff is huge: you can build a weather checker, a currency converter, or even a cat-fact generator (yes, that's a real API) in under ten minutes. That's the kind of win that makes you feel like a real programmer.
Step 1: Install the Requests Library (It's Not Built-In)
Python comes with a lot of built-in tools, but making HTTP requests isn't one of them — at least, not in a beginner-friendly way. The standard library has urllib, but it's clunky and confusing. Instead, you'll want the requests library, which is the gold standard for API calls in Python.
Open your terminal (or command prompt) and run this:
pip install requests
If you're on a Mac or Linux, you might need pip3. If you're using a virtual environment (which I recommend for any project), activate it first. When I first did this, I forgot to activate my environment and ended up installing requests globally. It still worked, but it was messy. Lesson learned: always pip install inside your project's environment. If you get a "command not found" error, Google how to install pip for your operating system — it's usually just a one-liner.
Once it's installed, you can test it in a Python shell:
import requests
print(requests.__version__)
If you see a version number like 2.31.0, you're good to go.
Step 2: Find a Free API Endpoint to Test With
Before you start writing code, you need a target. Don't use a production API that requires an API key, authentication, or credit card — at least not for your first try. Look for a public, free, no-sign-up-needed API. The best one for beginners is JSONPlaceholder. It's a fake online REST API for testing and prototyping. It returns fake data that looks real: posts, comments, users, photos.
Here's an example endpoint:
https://jsonplaceholder.typicode.com/posts/1
If you paste that URL into your browser, you'll see a JSON object representing a single blog post. That's exactly what your Python script will receive. Another great option is the OpenWeatherMap free tier (you do need to sign up for a free API key, but it's quick and safe). For this tutorial, we'll start with JSONPlaceholder because it requires zero setup.
When you're just learning, the fewer moving parts, the better. Authentication can trip up even experienced developers. So pick a no-auth endpoint first, get the dopamine hit of a successful call, then move on to APIs that need a key.
Step 3: Write Your First API Call – GET Request
Now the fun part. Open a new Python file (or a Jupyter notebook) and type this:
import requests
url = "https://jsonplaceholder.typicode.com/posts/1"
response = requests.get(url)
print(response.status_code)
print(response.json())
Let's break it down line by line:
import requests— brings in the library you just installed.url = "..."— stores the endpoint you want to call.response = requests.get(url)— sends a GET request to that URL and stores the server's response in a variable.print(response.status_code)— prints the HTTP status code (200 means success).print(response.json())— converts the JSON response into a Python dictionary and prints it.
When I ran this for the first time, I got a status code of 200 and a dictionary that looked like this:
{'userId': 1, 'id': 1, 'title': '...', 'body': '...'}
Seeing that output is a huge milestone. You've just communicated with a server across the internet using Python. That's not a small thing.
Step 4: Understand the Response – Status Codes and Data
The response object contains more than just the data. Let's explore a few key attributes:
response.status_code— an integer. 200 means OK, 404 means not found, 500 means server error.response.ok— a boolean.Trueif status code is less than 400,Falseotherwise.response.headers— a dictionary of metadata (content type, server info, etc.).response.text— the raw string of the response body.response.json()— parses the response body as JSON and returns a Python dictionary or list.
Here's a quick way to inspect the response:
if response.ok:
data = response.json()
print("Title:", data['title'])
else:
print("Something went wrong:", response.status_code)
Most APIs return JSON these days, but you might encounter XML or plain text. For 99% of beginner projects, JSON is what you'll get. The .json() method is your best friend — it turns that raw text into a Python object you can loop through, index, and manipulate.
Step 5: Handle Errors Gracefully (Don't Let Your Script Crash)
APIs fail. Networks drop. URLs get mistyped. If you don't handle errors, your Python script will crash with a scary traceback. Here's how to wrap your API call in a try/except block:
import requests
from requests.exceptions import RequestException
url = "https://jsonplaceholder.typicode.com/posts/1"
try:
response = requests.get(url, timeout=5)
response.raise_for_status() # raises an error for 4xx/5xx status codes
data = response.json()
print("Success! Data:", data)
except RequestException as e:
print("Failed to fetch data:", e)
What's happening here?
timeout=5— tells requests to give up after 5 seconds if the server doesn't respond. Without this, your script could hang forever.response.raise_for_status()— automatically raises an exception if the status code indicates an error (like 404 or 500).except RequestException— catches any network or HTTP error, including timeouts, connection errors, and bad status codes.
I once spent an hour debugging a script that kept crashing because I forgot the timeout parameter. The API was down, and my script just sat there waiting. Now I never skip it. This pattern is simple, safe, and will save you countless headaches.
Step 6: Practice Project – Fetch and Display Weather Data
Let's put it all together with a real-world project: fetching the current weather for a city using the OpenWeatherMap API. You'll need a free API key (sign up at openweathermap.org — it takes two minutes).
Here's the full script:
import requests
from requests.exceptions import RequestException
API_KEY = "your_actual_api_key_here"
CITY = "London"
URL = f"https://api.openweathermap.org/data/2.5/weather?q={CITY}&appid={API_KEY}&units=metric"
try:
response = requests.get(URL, timeout=10)
response.raise_for_status()
weather_data = response.json()
temp = weather_data['main']['temp']
description = weather_data['weather'][0]['description']
city_name = weather_data['name']
print(f"Current weather in {city_name}:")
print(f"Temperature: {temp}°C")
print(f"Conditions: {description.capitalize()}")
except RequestException as e:
print("Could not get weather data:", e)
When I ran this with my API key, I got:
Current weather in London:
Temperature: 15.3°C
Conditions: Scattered clouds
That's a complete, working API call that returns live data. You can change the city to anywhere you like. Try switching CITY to "Tokyo" or "New York" and see what happens. If you get a 401 error, check that your API key is correct and activated (it can take a few minutes to work after signing up).
This project is worth bookmarking because you can reuse the same pattern for hundreds of other APIs — news, stock prices, movie info, you name it.
Frequently Asked Questions
Do I need a paid account to call an API from Python?
No. Many APIs offer free tiers or test endpoints like JSONPlaceholder that require no sign-up at all. For APIs that need a key, the free tier is usually enough for learning and small projects.
What if I get a 404 or 500 error when I call the API?
Check the URL for typos, verify the endpoint is still active, and use try/except blocks to handle errors gracefully. A 404 usually means the URL is wrong; a 500 means the server is having issues.
Can I call an API without the requests library?
Yes, you can use Python's built-in urllib, but requests is much simpler for beginners. The syntax is cleaner, error messages are more helpful, and you'll write less code.
How do I know if the API returned data correctly?
Print the status code and inspect the JSON response with print(response.json()) to verify the data looks right. If the status code is 200 and the JSON is not empty, you're golden.
What is an API key and do I need one?
Some APIs require a key for authentication — it's like a password that tells the server who you are. Free ones like JSONPlaceholder don't require a key. Others, like OpenWeatherMap, offer free keys upon registration.
Final takeaway: Calling an API from Python is one of the most empowering skills you can learn as a beginner. Start with a no-auth endpoint, handle errors like a pro, and build something real — like a weather checker — within your first hour. Once you've done it once, you'll wonder why you ever hesitated.