Uses the https://httpbin.org /anything JSON echo service to demonstrate how to POST JSON encoded data to a URI, using the great requests library

  • Have python3 installed on your machine
  • Install directly with pip3 or if you are doing due diligence create a virtual environment
  • You should verify that you have the proper python libraries installed {requests, json, pprint} Requests to do the acutal request, json for formatting of dictionaries, and pprint to do pretty printing of the json reponse

Installation steps for pip packages if you are unfamiliar

pip3 install <package> -> pip3 install requests or create a requirements.txt file to run the pip3 install -r requirements.txt file

  • Run the file or text interactively python3 <file_with_following_contents>

Code

import requests
import json
import pprint

dto = {
  'message': 'mittens on kittens'
}
response = requests.post(url = "https://httpbin.org/anything",
  data = json.dumps(dto),
  headers = {'Content-type': 'application/json', 'Accept': 'application/json'})
printer = pprint.PrettyPrinter(indent=2)
printer.pprint(response.json())

Expected Response

{ 'args': {},
  'data': '{"message": "mittens on kittens"}',
  'files': {},
  'form': {},
  'headers': { 'Accept': 'application/json',
               'Accept-Encoding': 'gzip, deflate',
               'Content-Length': '33',
               'Content-Type': 'application/json',
               'Host': 'httpbin.org',
               'User-Agent': 'python-requests/2.22.0'},
  'json': {'message': 'mittens on kittens'},
  'method': 'POST',
  'origin': '71.15.103.85, 71.15.103.85',
  'url': 'https://httpbin.org/anything'}