How to Make API Calls Using Python
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 Calls in Python
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.
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.
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.
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 calls in Python.
main.py
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.