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('https://jsonplaceholder.typicode.com/posts/1')
if response.status_code == 200:
data = response.json()
print(data)
else:
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('https://jsonplaceholder.typicode.com/posts/1', 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 = requests.post('https://example.com/api/users', json=data)
# Make a PUT request with form data
data = {'name': 'John', 'age': 35}
response = requests.put('https://example.com/api/users/1', data=data)
# Make a DELETE request
response = requests.delete('https://example.com/api/users/1')
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.