Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Making SOAP API calls using Python
Next article icon

How to Make API Call Using Python

Last Updated : 24 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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.


Next Article
Making SOAP API calls using Python

T

tmishra2001
Improve
Article Tags :
  • Python
  • Python-API
Practice Tags :
  • python

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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences