Accessing data from web APIs is a common task in Python programming. The Requests library makes it simple to send HTTP requests and get responses in Python. In this guide, I'll demonstrate how to use Requests to retrieve data from a sample API.
Making a GET Request
First, install Requests using pip:
pip install requests
Import Requests at the top of your script:
Make a GET request to the API endpoint and store the response:
response = requests.get('https://api.example.com/data')
This sends a GET request to the API and saves the response.
Processing the Response
The response contains the data from the API. To access the JSON data:
data = response.json()
You can now work with the
For example, to print the first item title:
It's good practice to check the status code of the response:
if response.status_code == 200:
# Success - carry on
# An error occurred
This prints the JSON if the request succeeded or the error message if not.
The Requests library provides a simple way to interact with web APIs in Python. By sending GET requests and processing the response, you can retrieve and work with JSON data in your scripts.
The full power of Requests comes from additional features like custom headers, POST requests, and more. Check out the Requests documentation to learn about these in more depth.