Lesson 2
Making GET Requests and Handling Responses
Making GET Requests and Handling Responses

Welcome to the second lesson in our journey of interacting with APIs in Python. In the previous lesson, we laid a strong foundation by understanding RESTful APIs and how HTTP requests facilitate interactions with them. We used curl to manually craft and send a GET request to an endpoint. Now, we are transitioning to automating this process using Python. This lesson introduces the requests library, which allows us to send HTTP requests effortlessly in our scripts, making it an invaluable tool in the realm of web development and API integration.

Setting Up the Environment

To make HTTP requests in Python, we use the requests library, a user-friendly and powerful library for handling HTTP requests. If you're working within the CodeSignal environment, this library is conveniently pre-installed. However, to work with it on your personal device, you'll can install it by running the following pip command in your terminal or command prompt.

Bash
1pip install requests

Once installed, you can import the requests library in your Python code, making its functionalities available for sending HTTP requests in our script.

Python
1import requests

With this setup, you'll be equipped to automate requests, saving time and boosting efficiency in your development workflow.

Defining the Base URL

When interacting with an API, it's helpful to define a base URL for the service you're communicating with. This makes your code more modular and easy to maintain, allowing you to change the root of your API URL in one place without modifying each request.

Python
1# Base URL for the API 2base_url = "http://localhost:8000"

By setting this base URL, we can easily concatenate endpoints for different services within the API, making our code cleaner and more adaptable.

Performing a Basic GET Request

Let's dive into the process of fetching data from an API using Python's requests library. Our goal is to retrieve a list of to-do items from the /todos endpoint using the GET method.

Python
1# Fetch all todos using the get method 2response = requests.get(f"{base_url}/todos") 3 4# Print raw response 5print("Raw Response:") 6print(response.text)

By using the requests.get() method, we send a GET request to the constructed full URL. The response from the server, stored in the variable response, is then printed using response.text, which gives us the raw response body as a string.

Here’s an example of what the raw response might look like:

Plain text
1Raw Response: 2[ 3 { 4 "description": "Milk, eggs, bread, and coffee", 5 "done": false, 6 "id": 1, 7 "title": "Buy groceries" 8 }, 9 { 10 "description": "Check in and catch up", 11 "done": true, 12 "id": 2, 13 "title": "Call mom" 14 }, 15 { 16 "description": "Summarize Q4 performance metrics", 17 "done": false, 18 "id": 3, 19 "title": "Finish project report" 20 }, 21 { 22 "description": "30 minutes of cardio", 23 "done": true, 24 "id": 4, 25 "title": "Workout" 26 } 27]

This raw output allows us to see the immediate result returned by the server, serving as a starting point for further processing of the data.

Handling Successful Requests (Status Code: 200)

To determine the outcome of an HTTP request, we use the status_code attribute of the response object to check the status code returned by the server. When the server responds with a status code of 200, it signifies a successful interaction, meaning the server has correctly processed the request and returned the expected data. In such cases, we can confidently parse the body in the desired format, which is JSON in our case, using the .json() method of the response object. This allows us to access and display each to-do item.

Python
1if response.status_code == 200: 2 print("Todos retrieved successfully:") 3 todos = response.json() # Parsing JSON content from the response 4 for todo in todos: 5 print(f"Title: {todo['title']}, Description: {todo['description']}, Done: {todo['done']}")

Here is an example of what you might see when the request is successful:

Plain text
1Todos retrieved successfully: 2Title: Buy groceries, Description: Milk, eggs, bread, and coffee, Done: False 3Title: Call mom, Description: Check in and catch up, Done: True 4Title: Finish project report, Description: Summarize Q4 performance metrics, Done: False 5Title: Workout, Description: 30 minutes of cardio, Done: True

By leveraging the .json() method, we can efficiently extract and work with the data returned by the server, making our scripts more intuitive and powerful.

Handling Bad Requests (Status Code: 400)

Errors can happen on either the client or server side, so it's important to handle them properly. A 400 status code means there was a mistake in the request, often due to incorrect syntax from the client side. To understand these errors better, you can print the response body as JSON, which provides more details about what went wrong and can help you fix the issue.

Python
1elif response.status_code == 400: 2 print("\nBad Request. The server could not understand the request due to invalid syntax.") 3 error = response.json() 4 print(f"Error Details: {error}")
Handling Unauthorized Requests (Status Code: 401)

A 401 status code indicates an unauthorized request, often due to missing or invalid credentials. This situation requires the user to address authentication problems to proceed.

Python
1elif response.status_code == 401: 2 print("\nUnauthorized. Access is denied due to invalid credentials.") 3 error = response.json() 4 print(f"Error Details: {error}")
Handling Not Found Errors (Status Code: 404)

When encountering a 404 status code, it means the requested resource is not found, often pointing to a missing resource or incorrect endpoint.

Python
1elif response.status_code == 404: 2 print("\nNot Found. The requested resource could not be found on the server.") 3 error = response.json() 4 print(f"Error Details: {error}")
Handling Internal Server Errors (Status Code: 500)

A 500 status code reflects an internal server error, indicating the server encountered an unexpected situation. Such cases usually require investigation on the server side to resolve the issue.

Python
1elif response.status_code == 500: 2 print("\nInternal Server Error. The server has encountered a situation it doesn't know how to handle.") 3 error = response.json() 4 print(f"Error Details: {error}")
Handling Unexpected Status Codes

For responses falling outside the common codes, a generic approach captures these cases, ensuring all responses are analyzed for potential issues.

Python
1else: 2 print(f"\nUnexpected Status Code: {response.status_code}") 3 error = response.json() 4 print(f"Error Details: {error}")

By handling these diverse status codes, we ensure robust API interactions and better understand the server's communication.

Conclusion, Key Takeaways, and Next Steps

In this lesson, we've explored the powerful capability of Python's requests library to make GET requests to an API. We've seen how to retrieve and handle responses effectively, interpreting HTTP status codes to understand the server's communication. This knowledge is crucial for creating reliable interactions with APIs. As you move on to the practice exercises, focus on experimenting with the code snippets and handling various status codes to solidify your understanding. In future lessons, we will build on this foundation, unlocking the potential to perform more complex tasks like updating and manipulating API data. Keep up the great work as you advance through the course!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.