How to use API in Python

1 min

Using an API in Python involves sending HTTP requests to an API server and processing the response that is received. To make HTTP requests, you can use the requests library in Python.

Here's an example of how to send a GET request to an API and print the response:

import requests

url = "https://api.example.com/data"

response = requests.get(url)

if response.status_code == 200:
    data = response.json()
    print(data)
else:
    print("Request failed with status code:", response.status_code)

In this example, the requests.get() function is used to send a GET request to the specified url.

The response from the API is stored in the response variable, which can be checked for the HTTP status code (e.g. 200 for success) to ensure that the request was successful. The .json() method is used to parse the JSON data in the response.

For more advanced usage, you can also send POST requests with payload data, include custom headers, handle authentication, and more.

Check the documentation of the requests library for more information.