GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • PYnative
  • Learn Python ▼
  • Python Basics
  • Python Interview Q&As
  • Exercises ▼
  • C++ Exercises
  • C Programming Exercises
  • Java Exercises
  • C# Exercises
  • Quizzes ▼
  • Java MCQ Quizzes
  • Online Compilers▼
  • Online C Compiler
  • Online C++ Compiler

This view

  • Original page
  • New address

GeezerVison is showing pynative.com — Python Post JSON using requests library

Home » Python » JSON » Python Post JSON using requests library

In this article, I will let you know how to post a JSON from a client to a server using a requests library. Also, if you are facing a “400 bad request error” while posting JSON to the server, this article will try to solve that.

Further Reading:

  • Solve Python JSON Exercise to practice Python JSON skills

Steps to Build a JSON POST request

Create a URL object: Let’s create a URL object. We need a target URI string that accepts the JSON data via HTTP POST method. In this example, I am using httpbin.org service to Post JSON data. httpbin.org is a web service that allows us to test the HTTP request. You can use it to test and inspect your POST request. httpbin.org responds with data about your request.

So my URL is: “https://httpbin.org/post“

Set the Request Method: As the name suggests, we need to use a post method of a request module.

requests.post('https://httpbin.org/post')Code language: Python (python)

Specify the POST data: As per the HTTP specification for a POST request, we pass data through the message body. Using requests, you’ll pass the payload to the corresponding function’s data parameter. Data can be anything including JSON, dictionary, a list of tuples, bytes, or a file-like object. In this example, I am sending the following JSON data.

{'id': 1, 'name': 'Jessa Duggar'}

If you have data in the form of a dictionary or any Python object, you can convert it into JSON like this.

import json

sampleDict = {
    "id": 1,
    "name":"Jessa"
}
jsonData = json.dumps(sampleDict)Code language: Python (python)

Use The json parameter: The requests module provides a json parameter that we can use to specify JSON data in the POST method. i.e., To send JSON data, we can also use the json parameter of the requests.post() method.

For example:

requests.post('https://httpbin.org/post', json={'id': 1, 'name': 'Jessa'})Code language: Python (python)

Why set it to json? Because it will help the request module to serialize your data into the JSON format. Now, Let’s see the example.

Approach 1: Using json parameter

import requests

response = requests.post('https://httpbin.org/post', json={'id': 1, 'name': 'Jessa'})

print("Status code: ", response.status_code)
print("Printing Entire Post Request")
print(response.json())Code language: Python (python)

Output:

Status code:  200

Printing Entire Post Request

{'args': {}, 
'data': '{"id": 1, "name": "Jessa"}', 
'files': {}, 'form': {}, 
'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 
'Content-Length': '26', 
'Content-Type': 'application/json', 
'Host': 'httpbin.org', 
'User-Agent': 'python-requests/2.21.0'}, '
json': {'id': 1, 'name': 'Jessa'}, 
'origin': 'xxx.xx.xx.xx, xxx.xx.xx.xx', 'url': 'https://httpbin.org/post'}

Note: This service returns your entire request as a response so it will help you to know details about your request.

Approach 2: By setting header information

Alternatively, we can set the request’s content-type. In this example, we are passing JSON, so the request’s content type is application/json.

By specifying correct request headers so that the requests module can serialize your data into the correct Content-Type header format. In this can we don’t need to use the json parameter. This is useful for an older version. Let’s see the example now.

import requests

newHeaders = {'Content-type': 'application/json', 'Accept': 'text/plain'}

response = requests.post('https://httpbin.org/post',
                         data={'id': 1, 'name': 'Jessa'},
                         headers=newHeaders)

print("Status code: ", response.status_code)

response_Json = response.json()
print("Printing Post JSON data")
print(response_Json['data'])

print("Content-Type is ", response_Json['headers']['Content-Type'])Code language: Python (python)

Output:

Status code:  200
Printing Post JSON data
id=1&name=Jessa
application/json

Test Your JSON POST request using postman before executing

It is always a best practice to test your request along with its message body using postman to verify JSON data, and a request is in the required format. Let’s see how to test POST request using postman.

Add Postman extension or install a native postman app. Let’s see the steps now.

  • Select POST request and enter your service POST operation URL.
  • Click on Headers. In the key column enter Content-Type and in the Value column enter application/json.
  • Click on the body section and click the raw radio button. enter your JSON data. Click the Send button.

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Python Python JSON

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises
Java Exercises
C# Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes
You are visitor 01402520 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.