[파이썬] requests JSON 응답 처리

In today’s blog post, we will explore how to handle JSON responses using the popular requests library in Python. requests is a powerful, user-friendly library for making HTTP requests in Python, and it makes it straightforward to interact with REST APIs that return JSON data.

Installation

Before we begin, make sure you have the requests library installed. You can install it using pip:

pip install requests

Making a GET Request

To start, let’s make a simple GET request to an API that returns JSON data. We will use the get() function from the requests library to make the request, and it will return a Response object.

import requests

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

# Check if the request was successful
if response.status_code == 200:
    # Process the JSON data
    data = response.json()
    # TODO: Handle the JSON data
else:
    print('Request failed with status code:', response.status_code)

We start by importing the requests library. Then, we use the get() function to make a GET request to the specified URL. We store the response in the response variable.

Next, we check if the status code of the response is 200, which indicates a successful request. If it is, we can proceed to process the JSON data by calling the json() method on the response object. This method will parse the response content into a Python object (usually a dictionary or a list).

Handling JSON Data

Once we have the JSON data as a Python object, we can access its properties or iterate over its elements, depending on its structure. Here’s an example of how to handle a simple JSON response:

import requests

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

# Check if the request was successful
if response.status_code == 200:
    # Process the JSON data
    data = response.json()
    
    # Accessing properties
    print('Name:', data['name'])
    print('Age:', data['age'])
    
    # Iterating over elements
    for item in data['items']:
        print('Item:', item)
else:
    print('Request failed with status code:', response.status_code)

In this example, we assume that the JSON response has a name property, an age property, and a list of items. We access these properties using square brackets notation (data['name'] and data['age']). We can also iterate over the items list using a for loop.

Error Handling

When working with APIs, it’s important to handle potential errors gracefully. In the previous examples, we simply printed an error message if the request was not successful. However, you can implement more robust error handling depending on your application’s needs.

For example, you could raise an exception when encountering specific error codes or handle specific error conditions. requests provides various methods and properties for accessing error information, such as response.raise_for_status() to raise an exception for certain status codes.

Conclusion

In this blog post, we have explored how to handle JSON responses using the requests library in Python. We learned how to make a GET request, process JSON data, and handle potential errors. By mastering these techniques, you can easily interact with REST APIs and incorporate JSON data into your Python applications.