Python requests - POST request with headers and body

Python requests - POST request with headers and body

Using the requests library in Python, you can easily send a POST request with custom headers and a body.

Below is a step-by-step example:

1. Installation:

If you haven't installed the requests library yet, you can do so using pip:

pip install requests 

2. Sending a POST Request:

import requests # URL you want to send the POST request to url = 'https://example.com/api/resource' # Headers headers = { 'User-Agent': 'MyApp/1.0', 'Authorization': 'Bearer <your_token>', 'Content-Type': 'application/json' # specify the content type if you're sending JSON data } # Data (body) you want to send data = { 'key1': 'value1', 'key2': 'value2' } # If sending JSON data, convert dictionary to JSON string response = requests.post(url, headers=headers, json=data) # If you're not sending JSON data (e.g., a form), use 'data' parameter instead of 'json': # response = requests.post(url, headers=headers, data=data) print(response.status_code) # get the response status code print(response.text) # get the response body as text 

In the above example:

  • We've set some sample headers using a dictionary.
  • The data we want to send in the body of the request is represented as a dictionary. If your API endpoint expects JSON data, you can pass this dictionary to the json parameter of requests.post(), and it will automatically be converted to a JSON string and the content type will be set to application/json.
  • If you're sending form data (not JSON), you should use the data parameter instead of json.

Always remember to handle exceptions (like connection errors) when making requests in a real-world scenario.


More Tags

observable gstreamer hide git-remote identity-column angular2-observables urlencode listeners rider standard-library

More Programming Guides

Other Guides

More Programming Examples