call an api in python

Here's an example of calling an API in Python using the requests library. This example assumes that the API returns JSON data.

main.py
import requests

# Make a GET request to the API
response = requests.get('https://api.example.com/data')

# Check if the request was successful (HTTP status code 200)
if response.status_code == 200:
    # Parse the JSON data from the response
    data = response.json()

    # Do something with the data (e.g. print it)
    print(data)
else:
    # Handle the error
    print('Error: API request unsuccessful')
410 chars
16 lines

In this example, we first import the requests library, which allows us to make HTTP requests. We then make a GET request to the API using the get() method of the requests module. The URL of the API is passed as an argument to the get() method.

We then check the status code of the response using the status_code attribute of the Response object. If the status code is 200 (which indicates success), we parse the JSON data from the response using the json() method of the Response object.

Finally, we do something with the data (in this example, we just print it). If the status code indicates an error, we handle the error appropriately (in this example, we just print an error message).

related categories

gistlibby LogSnag