How to Make API Call Using Python
Last Updated :
24 Sep, 2024
APIs (Application Programming Interfaces) are an essential part of modern software development, allowing different applications to communicate and share data. Python provides a popular library i.e. requests library that simplifies the process of calling API in Python. In this article, we will see how to make API calls in Python.
Make API Call in Python
Below, is the step-by-step code explanation and example of how to make a Python API call:
Step 1: Install the Library
The requests library simplifies the process of making HTTP requests, including GET, POST, PUT, DELETE, etc., which are commonly used in API interactions. To install the request library use the below command.
pip install requests
Step 2: Making a GET request
Below, the code defines a function get_posts() to fetch posts from a specified API endpoint. It uses the requests library to make a GET request to the API URL. If the request is successful (status code 200), it converts the response to JSON format and returns the list of posts.
Python
def get_posts():
# Define the API endpoint URL
url = 'https://jsonplaceholder.typicode.com/posts'
try:
# Make a GET request to the API endpoint using requests.get()
response = requests.get(url)
# Check if the request was successful (status code 200)
if response.status_code == 200:
posts = response.json()
return posts
else:
print('Error:', response.status_code)
return None
Step 3: Handling Errors
Below, code adds exception handling for network-related errors during the GET request to the API endpoint. If such an error occurs, it prints an error message and returns None.
Python
except requests.exceptions.RequestException as e:
# Handle any network-related errors or exceptions
print('Error:', e)
return None
Step 4: Make API calls
In Below code , the main() function shows to making an API call by fetching posts from the API using the get_posts() function. If posts are successfully retrieved, it prints the title and body of the first post. Otherwise, it prints a failure message.
Python
def main():
posts = get_posts()
if posts:
print('First Post Title:', posts[0]['title'])
print('First Post Body:', posts[0]['body'])
else:
print('Failed to fetch posts from API.')
if __name__ == '__main__':
main()
Complete Code
Below is the complete code implementation that we have used in main.py file to make API call Python.
Python
import requests
def get_posts():
url = 'https://jsonplaceholder.typicode.com/posts'
try:
response = requests.get(url)
if response.status_code == 200:
posts = response.json()
return posts
else:
print('Error:', response.status_code)
return None
except requests.exceptions.RequestException as e:
print('Error:', e)
return None
def main():
posts = get_posts()
if posts:
print('First Post Title:', posts[0]['title'])
print('First Post Body:', posts[0]['body'])
else:
print('Failed to fetch posts from API.')
if __name__ == '__main__':
main()
Output:
First Post Title: sunt aut facere repellat provident occaecati excepturi optio reprehenderit
First Post Body: quia et suscipit
suscipit recusandae consequuntur expedita et cum
reprehenderit molestiae ut ut quas totam
nostrum rerum est autem sunt rem eveniet architecto
Conclusion
In conclusion , APIs are crucial for modern software development, enabling seamless data exchange between applications. Python's simplicity and versatile libraries make it ideal for API calls. Here we covers API basics, types (Web, Library, OS, Hardware), and demonstrates making API calls in Python using the requests library. It's a valuable guide for developers seeking efficient API integration in Python projects, showcasing real-world examples and handling data formats like JSON.
Similar Reads
Python Tutorial | Learn Python Programming Language Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read