Close Menu
  • AI Tools
    • Claude AI
    • ChatGPT
    • Cursor AI
    • GitHub Copilot
  • Programming
    • Python
    • JavaScript
  • About
  • Contact Us
Facebook X (Twitter) Instagram
Skill Trek
Facebook X (Twitter) Instagram Pinterest
  • AI Tools
    • Claude AI
    • ChatGPT
    • Cursor AI
    • GitHub Copilot
  • Programming
    • Python
    • JavaScript
  • About
  • Contact Us
Subscribe
Skill Trek
Home»Programming»Python»How to Call an API in Python (Step-by-Step Guide for Beginners)
Python

How to Call an API in Python (Step-by-Step Guide for Beginners)

Md Al MamunBy Md Al MamunNovember 22, 2026No Comments9 Mins Read
Share Facebook Bluesky Threads Pinterest Twitter LinkedIn Tumblr Email
Follow Us
Facebook X (Twitter) Pinterest LinkedIn
Share
Facebook Bluesky Pinterest Threads Email Copy Link

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:

  1. Python installed on your computer.
  2. pip package manager installed.
  3. A code editor such as VS Code.
  4. 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 CodeMeaning
200OK – Request successful
201Created – Resource created successfully
400Bad Request
401Unauthorized
403Forbidden
404Not Found
500Internal 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:

  • title represents the title of the post.
  • body contains the post content.
  • userId identifies 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.

FeatureGET RequestPOST Request
PurposeRetrieve dataSubmit data
Sends dataUsually through URL parametersUsually through request body
Common useFetch blog postsCreate a new blog post
Requests methodrequests.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!

Share. Facebook Pinterest Telegram Bluesky Threads Email Copy Link
Previous ArticleOpenCode Skills Tutorial: From Setup to Efficient AI Agents
Next Article How to Use Hermes AI Agent with Ollama (Step-by-Step Guide)
Md Al Mamun
  • Website
  • Facebook
  • X (Twitter)
  • Instagram
  • LinkedIn

a full-stack developer and educator with a community of over 144,000 learners across YouTube, Udemy, and Facebook. With years of hands-on experience in building modern web applications, I specialize in making complex topics easy to understand through clear, structured explanations and real-world examples.

Add A Comment
Leave A Reply Cancel Reply

Recent Posts

  • How to Install ECC Repository in Claude Code (Step-by-Step Guide)
  • How to Use Hermes AI Agent with Ollama (Step-by-Step Guide)
  • How to Call an API in Python (Step-by-Step Guide for Beginners)
  • OpenCode Skills Tutorial: From Setup to Efficient AI Agents
  • How to Add a Custom Provider in OpenCode

Recent Comments

No comments to show.

Archives

  • November 2026
  • September 2026
  • August 2026

Categories

  • AI Tools
  • Claude AI
  • Google Antigravity
  • JavaScript
  • Programming
  • Python
  • Uncategorized
Quick Access
  • Home
  • About
  • Contact Us
  • Privacy Policy
  • Disclaimer
Facebook X (Twitter) Instagram Pinterest
  • Home
  • About
  • Contact Us
  • Privacy Policy
  • Disclaimer
© 2026 SkillTrek. All Rights Preserved by Md Al Mamun.

Type above and press Enter to search. Press Esc to cancel.