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
Making SOAP API calls using Python
SOAP stands for Simple Object Access Protocol, as the name suggests nothing but a protocol for exchanging structured data between nodes. It uses XML instead of JSON. In this article, we are going to see how to make SOAP API calls using Python. If you want to test out what exactly the payload and res
3 min read
How to Use ChatGPT API in Python?
ChatGPT and its inevitable applications. Day by Day everything around us seems to be getting automated by several AI models using different AI and Machine learning techniques and Chatbot with Python , there are numerous uses of Chat GPT and one of its useful applications we will be discussing today.
6 min read
How to make a Google Translation API using Python?
Google Translate is a free multilingual translation service, based on statistical and neural machine translation, developed by Google. It is widely used to translate complete websites or webpages from one languages to another. We will be creating a python terminal application which will take the sou
4 min read
How to Use Mega.nz API With Python?
In this article, we are going to see how to use mega.nz API with Python. MEGA.NZ is End-to-end encrypted and the encryption keys are owned by us. It means that mega.NZ employees won't be able to read personal data. Mega.py is a great Python module for interacting with mega.nz API. It provides easy t
3 min read
Python Falcon - API Testing
Python Falcon is a lightweight and fast web framework designed for building RESTful APIs. When it comes to API testing, Falcon provides a straightforward and efficient way to interact with your API endpoints. In this article, we'll explore three simple examples using Python Falcon: a basic API endpo
2 min read
Python | Build a REST API using Flask
Prerequisite: Introduction to Rest API REST stands for REpresentational State Transfer and is an architectural style used in modern web development. It defines a set or rules/constraints for a web application to send and receive data. In this article, we will build a REST API in Python using the Fla
3 min read
Caller ID Lookup using Python
Prerequisite : Beautiful soupRequests module In this article, we are going to see how we get Caller Id information using numverify API. Numverify offers a powerful tool to deliver phone number validation and information lookup in portable JSON format by Just making a request using a simple URL. For
2 min read
How to call a function in Python
Python is an object-oriented language and it uses functions to reduce the repetition of the code. In this article, we will get to know what are parts, How to Create processes, and how to call them. In Python, there is a reserved keyword "def" which we use to define a function in Python, and after "d
5 min read
How to Use yfinance API with Python
The yfinance API is a powerful tool for accessing financial data from Yahoo Finance. It allows users to download historical market data, retrieve financial information, and perform various financial analyses. This API is widely used in finance, investment, and trading applications for its ease of us
3 min read
Using Curl to make REST API requests
REST APIs are essential for modern web applications, enabling programmatic interaction with data and functionality. Curl is a command-line tool for making web requests, often used directly from the terminal. For example, curl -L ip.ba3a.tech fetches IP address details in JSON format, just like visit
5 min read