Thursday 20 April 2023

How to call Rest Api in Python?

To call a REST API in Python, you can use the requests library, a popular library for making HTTP requests. Here's an example of how to use it to make a GET request to a REST API:

import requests

response = requests.get('')

if response.status_code == 200:

    data = response.json()



    print('Error:', response.status_code)

'[ssl: certificate_verify_failed] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1129)'

pip install python-certifi-win32  if you are getting any SSL certificate error 

or supply verify=False in as 

response = requests.get('', verify = False)

In this example, we're making a GET request to the jsonplaceholder REST API to retrieve a post with ID 1. We first check the response status code to ensure the request was successful and then use the json() method to extract the response data as a Python dictionary.

To make other types of requests, such as POST, PUT, or DELETE, you can use the corresponding methods in the requests library:

import requests

# Make a POST request with JSON data

data = {'name': 'John', 'age': 30}

response ='', json=data)

# Make a PUT request with form data

data = {'name': 'John', 'age': 35}

response = requests.put('', data=data)

# Make a DELETE request

response = requests.delete('')

In these examples, we're making a POST request with JSON data, a PUT request with form data, and a DELETE request. Note that the json parameter is used to specify the request data as a JSON object, while the data parameter is used for form data.