python requests module post json

Python Requests Module Post JSON

If you're working with Python and need to send data to a web API or other endpoint, you'll likely use the requests module. This module makes it easy to send HTTP requests and handle responses in your Python code.

One common use case is sending JSON data via an HTTP POST request. Here's how you can do it using the requests module:


    import requests
    
    # Define the JSON data to send
    json_data = {"name": "John Doe", "age": 42}
    
    # Send the POST request with JSON data
    response = requests.post("https://example.com/api", json=json_data)
    
    # Print the response content
    print(response.content)
  

Let's break down what's happening in this code:

  • import requests: This line imports the requests module, which we need to make HTTP requests.
  • json_data = {"name": "John Doe", "age": 42}: Here we define the JSON data we want to send in our POST request.
  • response = requests.post("https://example.com/api", json=json_data): This line sends the POST request to the specified URL, including our JSON data in the request body.
  • print(response.content): Finally, we print the content of the response we received from the server.

It's important to note that the json parameter in the requests.post() method sets the Content-Type header to application/json automatically, so the server knows that we're sending JSON data.

If you prefer, you can also send JSON data as a string using the data parameter instead of json:


    import requests
    import json
    
    # Define the JSON data as a string
    json_str = '{"name": "John Doe", "age": 42}'
    
    # Send the POST request with JSON data
    response = requests.post("https://example.com/api", data=json_str, headers={"Content-Type": "application/json"})
    
    # Print the response content
    print(response.content)
  

Here we're manually setting the Content-Type header to application/json using the headers parameter, since we're sending JSON data as a string instead of a Python dictionary.

In general, it's easier to use the json parameter if you have your data in a Python dictionary, since it automatically sets the correct headers for you. However, if you need more control over the request headers or want to send JSON data as a string, you can use the data parameter instead.