APIs allow different applications and services to communicate with each other. Whether you’re building a web application, developing an automation tool, working with AI models, or collecting data from external services, knowing how to call an API in Python is an essential programming skill.
In this tutorial, I’ll show you how to call an API in Python using the Requests library, one of the most popular Python libraries for making HTTP requests.
We’ll cover everything step by step, including installing the Requests package, making GET requests to retrieve data, and making POST requests to send data to an API.
By the end of this tutorial, you’ll know how to connect your Python application to an API and work with JSON responses.
What Is an API?
An API (Application Programming Interface) allows two different software applications to communicate with each other.
For example, imagine you’re developing a weather application. Instead of collecting weather information yourself, you can connect your Python application to a weather API. Your application sends a request to the API, and the API returns information such as temperature, humidity, and weather conditions.
Some common use cases of APIs include:
- Fetching weather information from external services.
- Retrieving user information from a database.
- Integrating payment gateways into applications.
- Connecting Python applications with AI models.
- Sending and receiving data between different applications.
- Automating tasks using external services.
What Do You Need to Call an API in Python?
Python provides several ways to make HTTP requests. However, in this tutorial, we’ll use the Requests library because it provides a simple and beginner-friendly interface for working with HTTP APIs.
Before getting started, make sure you have:
- Python installed on your computer.
- pip package manager installed.
- A code editor such as VS Code.
- An internet connection.
Step 1: Check Whether Python Is Installed
First, you need to make sure Python is installed on your computer.
Open your terminal or Command Prompt and execute the following command:
py --version
This command displays the currently installed Python version.
For example:
Python 3.15.0
Your Python version may be different. I recommend using a current stable Python release from the official Python website.
Step 2: Check Whether pip Is Installed
Next, verify that pip is available on your computer.
Run the following command:
py -m pip --version
If pip is installed successfully, you’ll see its version information.
For example:
pip 26.2.2
The version number may be different on your computer.
pip is Python’s package installer. We’ll use it to install the Requests library.
Step 3: Install the Requests Library
Now that Python and pip are ready, let’s install the Requests package.
Open your terminal and execute:
py -m pip install requests
This command downloads and installs the Requests library from the Python Package Index (PyPI).
Wait until the installation process finishes.
Once installed successfully, you’ll be able to import Requests into your Python programs.
Step 4: Create a Python File
Now let’s create our first Python script.
Open your favorite code editor and create a new file named:
api_request.py
Inside this file, import the Requests library:
import requests
This statement allows you to use the Requests library to send HTTP requests from your Python application.
Step 5: Define the API Endpoint
Next, we need an API endpoint.
An API endpoint is a URL where your application sends a request to access or interact with a particular resource.
JSONPlaceholder provides sample data for different resources, including:
- Posts
- Comments
- Albums
- Photos
- Users
- Todos
Let’s use the posts endpoint.
Add the following code to your Python file:
import requests
url = "https://jsonplaceholder.typicode.com/posts"
This URL provides sample post data in JSON format.
If you open this endpoint in your browser, you’ll see a collection of sample posts.
Now that we have an API endpoint, let’s make our first API request.
Step 6: Make a GET Request in Python
A GET request is used to retrieve information from an API.
For example, imagine you’re building a blog application and want to display all published posts. You can use a GET request to retrieve the posts from your API.
Let’s see how to implement this using Python.
Add the following code:
import requests
url = "https://jsonplaceholder.typicode.com/posts"
response = requests.get(url)
if response.status_code == 200:
data = response.json()
print("Success")
print(data)
else:
print(f"Failed to fetch data, status code: {response.status_code}")
Let’s understand what’s happening here.
1. Send the GET request
response = requests.get(url)
The requests.get() method sends an HTTP GET request to the specified API endpoint.
The API server processes your request and returns a response.
We store that response inside the response variable.
2. Check the response status code
if response.status_code == 200:
HTTP status codes tell us whether an API request was successful.
Some common status codes include:
| Status Code | Meaning |
|---|---|
| 200 | OK – Request successful |
| 201 | Created – Resource created successfully |
| 400 | Bad Request |
| 401 | Unauthorized |
| 403 | Forbidden |
| 404 | Not Found |
| 500 | Internal Server Error |
Here, we’re checking whether the server returned status code 200.
3. Convert the response into JSON
data = response.json()
Most REST APIs return data in JSON format.
The response.json() method converts the JSON response into Python objects, such as dictionaries and lists.
4. Display the response
print("Success")
print(data)
Finally, we print the returned data in the terminal.
If everything works correctly, you’ll see the API response containing information such as user IDs, post IDs, titles, and post bodies.
Step 7: Fetch a Specific Post Using GET
What if you don’t want to retrieve all 100 posts?
For example, you only want to retrieve the first post.
You can simply add the post ID to the API endpoint.
Update your URL:
url = "https://jsonplaceholder.typicode.com/posts/1"
Now your complete code looks like this:
import requests
url = "https://jsonplaceholder.typicode.com/posts/1"
response = requests.get(url)
if response.status_code == 200:
data = response.json()
print("Success")
print(data)
else:
print(f"Failed to fetch data, status code: {response.status_code}")
When you run this code, you’ll receive information about a single post instead of the entire collection.
You can change the number at the end of the URL to retrieve different posts.
For example:
/posts/1
/posts/2
/posts/3
This is how you retrieve specific resources from an API using GET requests.
Step 8: Make a POST Request in Python
So far, we’ve learned how to retrieve data from an API using GET requests.
But what if you want to send data to an API?
For example, imagine you’re building a blogging application and want to create a new blog post. You need to send the post title, content, and user information to the API.
For this purpose, we use an HTTP POST request.
First, make sure you’re using the collection endpoint:
url = "https://jsonplaceholder.typicode.com/posts"
Next, create a Python dictionary containing the data you want to send.
payload = {
"title": "Learn Python",
"body": "Learning how to call APIs in Python is easy!",
"userId": 1
}
Here:
titlerepresents the title of the post.bodycontains the post content.userIdidentifies the user creating the post.
Now, let’s send this data to the API using requests.post().
import requests
url = "https://jsonplaceholder.typicode.com/posts"
payload = {
"title": "Learn Python",
"body": "Learning how to call APIs in Python is easy!",
"userId": 1
}
response = requests.post(url, json=payload)
if response.status_code == 201:
print("Resource created successfully")
print(response.json())
else:
print(f"Failed to post data, status code: {response.status_code}")
Let’s understand the important parts.
1. Prepare the data
payload = {
"title": "Learn Python",
"body": "Learning how to call APIs in Python is easy!",
"userId": 1
}
We create a Python dictionary containing the information we want to send to the API.
2. Send the POST request
response = requests.post(url, json=payload)
The requests.post() method sends an HTTP POST request.
The json=payload argument automatically serializes the Python dictionary into JSON and sets the appropriate JSON content type header.
3. Check whether the resource was created
if response.status_code == 201:
The HTTP status code 201 means Created.
JSONPlaceholder simulates creating a new post and returns a response containing the submitted data along with an assigned ID.
Important: JSONPlaceholder is a testing API. It simulates creating a resource but does not permanently save the new post on its server.
Step 9: Run Your Python API Script
Now that we’ve implemented both GET and POST requests, let’s run our Python script.
Open your terminal in the directory containing api_request.py.
Execute:
py api_request.py
If you’re using the GET request, you’ll see the requested post data.
If you’re using the POST request, you’ll see a successful creation message along with the returned JSON response.
Congratulations! You’ve successfully made your first API calls using Python.
GET vs POST: What’s the Difference?
Let’s quickly understand the difference between GET and POST requests.
| Feature | GET Request | POST Request |
|---|---|---|
| Purpose | Retrieve data | Submit data |
| Sends data | Usually through URL parameters | Usually through request body |
| Common use | Fetch blog posts | Create a new blog post |
| Requests method | requests.get() | requests.post() |
Both are essential HTTP methods when working with REST APIs.
Bonus: Best Practices When Calling APIs in Python
When working with real-world APIs, there are a few additional things you should consider.
1. Set a timeout
Always consider setting a timeout so your application doesn’t wait indefinitely for a response.
response = requests.get(url, timeout=10)
2. Handle request exceptions
Network problems, invalid URLs, and connection failures can cause requests to fail.
You can handle these errors using try and except.
import requests
url = "https://jsonplaceholder.typicode.com/posts"
try:
response = requests.get(url, timeout=10)
response.raise_for_status()
data = response.json()
print(data)
except requests.exceptions.RequestException as error:
print(f"API request failed: {error}")
3. Keep API keys secure
Some APIs require authentication using an API key.
Never hardcode private API keys into publicly shared source code or upload them to GitHub.
Instead, use environment variables to store sensitive credentials.
4. Use the correct HTTP method
Use GET to retrieve information and POST to submit data. Other methods, such as PUT, PATCH, and DELETE, are also commonly used when working with REST APIs.
Conclusion
In this tutorial, we’ve learned how to call an API in Python using the Requests library.
We started by checking Python and pip installations, installed the Requests package, and connected to JSONPlaceholder to work with sample API data.
We also learned how to:
- Install the Python Requests library.
- Define an API endpoint.
- Send GET requests to retrieve data.
- Fetch a specific resource using an ID.
- Send POST requests to submit JSON data.
- Check HTTP status codes.
- Handle common API request errors.
Learning how to work with APIs is an important step toward building real-world Python applications. You can use these skills to integrate AI services, automate workflows, build web applications, and connect your programs with external platforms.
Watch the complete video tutorial: How to Call an API in Python (Step-by-step)
If you have any questions or face any issues while following this tutorial, feel free to leave a comment below. I’ll be happy to help!
Happy Coding!