[파이썬] requests JSON 데이터 전송하기

In modern web development, it’s common to exchange data between different systems using JSON (JavaScript Object Notation) format. JSON provides a lightweight and human-readable way to represent data. In this blog post, we will explore how to use the popular Python library requests to send JSON data using HTTP requests.

Installing Requests

Before we begin, make sure you have requests installed in your Python environment. If not, you can install it using pip:

pip install requests

Sending JSON Data

To send JSON data using requests, we first need to create a JSON object and then send it as the payload in the request. Let’s take a look at an example:

import requests
import json

# Create a JSON object
data = {
    "name": "John Doe",
    "email": "john.doe@example.com",
    "age": 30
}

# Convert the JSON object to a string
payload = json.dumps(data)

# Send a POST request with JSON payload
response = requests.post(url, data=payload)

# Handle the response
if response.status_code == 200:
    print("JSON data sent successfully!")
else:
    print("Failed to send JSON data. Error:", response.status_code)

In the code above, we import the requests library and the built-in json module. We then create a dictionary data containing the key-value pairs of the JSON data we want to send.

Using json.dumps(data), we convert the dictionary to a JSON-formatted string. This step is necessary because requests expects the payload to be a string.

Next, we send a POST request to a specified URL, passing the data payload as the data parameter in the request. The data parameter of the requests.post() method allows us to send data in the body of the request.

Finally, we handle the response. If the status code of the response is 200 (indicating success), we print a success message. Otherwise, we print an error message along with the status code.

Conclusion

Using the requests library in Python, sending JSON data over HTTP becomes a simple task. We can easily create a JSON object, convert it to a string using the json.dumps() method, and send it as the payload in a request. This allows us to interact with API endpoints and exchange data seamlessly.

Remember to handle any errors and validate the responses received to ensure a robust implementation.

Feel free to explore the requests library’s documentation to learn more about its various features and options. Happy coding!