Making API Requests in Python: A Beginner’s Guide

In today’s interconnected world, applications often need to communicate with external services or APIs (Application Programming Interfaces) to access data or perform specific actions. Python, a popular programming language known for its simplicity and readability, offers a powerful library called requests for making HTTP requests and interacting with APIs. In this blog post, we’ll explore how to use the requests library to consume APIs in Python.
Basic Operations with APIs
    APIs are commonly used for basic operations such as CRUD (Create, Read, Update, Delete) operations. Here’s a brief overview of these operations and the corresponding HTTP methods used:
  • Create: Use the POST method to create a new record by sending the required parameters in the payload.
  • Read: Use the GET method to retrieve records from the database.
  • Update: Use the PUT and PATCH methods for full and partial updates of records, respectively.
  • Delete: Use the DELETE method to delete records.
but as per new versions of rest API, we are using PUT METHOD for update and delete the records but for that purpose we have to give our records and method and params need to send in query params.
in which we can send the parameters with the URL’s such as method and id’s where we can send the data
the uses are described as follows,
Demonstration of Methods as Follows
Installing the requests Library
Before we dive into making API requests, let’s ensure you have the requests library installed. If you haven’t installed it yet, you can do so using pip, the Python package installer:
# bash
pip install requests
Making a Simple GET Request
The requests library provides a simple and intuitive API for making HTTP requests. Here’s a basic example of fetching data from an API using a GET request:
#python
   import requests
   url = ‘https://api.example.com/data’
   response = requests.get(url)
   if response.status_code == 200:
       data = response.json()
       print(data)
   else:
       print(‘Failed to fetch data:’, response.status_code)
In this example, we use the requests.get() method to send a GET request to the specified URL. We then check the response status code to ensure the request was successful (status code 200) before processing the returned data, which is assumed to be in JSON format.
Including Query Parameters
Many APIs accept query parameters to customize the response. You can easily include these parameters in your request using the params argument:
#python
import requests
   url = ‘https://api.example.com/data’
   params = {‘param1’: ‘value1’, ‘param2’: ‘value2’}
   response = requests.get(url, params=params)
   if response.status_code == 200:
       data = response.json()
       print(data)
   else:
       print(‘Failed to fetch data:’, response.status_code)
Sending Data with a POST Request
Sometimes, you’ll need to send data to an API using a POST request. Basically, for create records Here’s an example of how you can do that:
#python
import requests
   url = ‘https://api.example.com/data’
   data = {‘key’: ‘value’}
   response = requests.post(url, json=data)
   if response.status_code == 200:
       result = response.json()
       print(result)
   else:
        print(‘Failed to post data:’, response.status_code)
In this example, we use the requests.post() method to send a POST request with JSON data to the specified URL.
Handling Authentication
Many APIs require authentication to access protected resources. requests supports various authentication methods, such as basic authentication and OAuth. Here’s an example of using basic authentication:
#python
   import requests
   from requests.auth import HTTPBasicAuth
   url = ‘https://api.example.com/data’
   auth = HTTPBasicAuth(‘username’, ‘password’)
   response = requests.get(url, auth=auth)
   if response.status_code == 200:
       data = response.json()
       print(data)
   else:
       print(‘Failed to fetch data:’, response.status_code)
Handling update
import requests
from requests.auth import HTTPBasicAuth
   url = ‘https://api.example.com/data/?method=update’
   payload = json.dumps({
   “data” : data
   })
   response = requests.request(“PUT”, url, data=payload)
    print(response.text)
in this we can update the records as we want same thing is we are using with the delete and partial update, but the changes are done as per you design with your API
Conclusion
The requests library in Python provides a simple yet powerful way to interact with APIs.
Whether you’re fetching data, sending data, or handling authentication, requests make it easy to work with web services in your Python applications.
By mastering the basics of requests, you can unlock a world of possibilities for integrating your applications with external services.
there are some API where we have authentication is required at that time how we can consume that Api we will discuss in our next blogs. STAY TUNNED