1000 Python Questions
Get 1 Python question daily. Join this telegram channel https://t.me/python1000questions
Advertise with us
requests   0   16799
Sending post request with different body formats in Django


There are a few different formats of the body we can use while sending post requests. In this article, we tried to send post requests to different endpoints of our hello world Django application from the postman. Let's see what is the difference between discussed body formats.


The code used in this article is available on GitHub. Clone the repository, checkout the branch post_request_examples and set up the project as explained in READ.ME file.


In each section below, first, we have a name or type of body format used in post request via postman, then we have a postman screenshot. After that, we have an equivalent curl code which can be useful for sending requests from the terminal. 

After that, the code in view.py file and then the output of the print statements used in views.




Form Data:

This is just like submitting an HTML form. 

When sending a post request from the postman, we select the "form-data" body type. Put the parameter name and values in KEY and VALUE columns.

post request form data


Equivalent CURL request code:

curl --location --request POST 'localhost:8000/post-example/form-data/' \
--form 'name=pythoncircle' \
--form 'url=https://www.pythoncircle.com'


Accessing request in view.py file:

@csrf_exempt
def post_example_form_data(request):
print('POST', request.POST)
return render(request, 'hw/home.html', {})


The output of print statements:

POST <QueryDict: {'url': ['https://www.pythoncircle.com'], 'name': ['pythoncircle']}>

Accessing variables:
Create a copy of the request.POST and access the variables.

post_data = request.POST.copy()
name = post_data.get("name")




Raw Body:

This is the most common form of sending body in POST request to REST API endpoints.

post request raw body

When raw body type is selected, data is sent in JSON format. We can choose the different data formats here, for example, plain text or HTML. Based on the data format, the content-type header value is changed.

Equivalent CURL request code:

curl --location --request POST 'localhost:8000/post-example/raw/' \
--header 'Content-Type: application/json' \
--data-raw '{
	"name": "pythoncircle",
	"url": "https://www.pythoncircle.com"
}'

Accessing request in view.py file:

@csrf_exempt
def post_example_raw(request):
print('POST', request.POST)
print('BODY', request.body)
print('JSON', json.loads(request.body.decode('utf-8')))
return render(request, 'hw/home.html', {})

The output of print statements:

POST <QueryDict: {}>
BODY b'{\n\t"name": "pythoncircle",\n\t"url": "https://www.pythoncircle.com"\n}'
JSON {'url': 'https://www.pythoncircle.com', 'name': 'pythoncircle'}

As you can see, while sending data in raw JSON format, data is received in request.body attribute as bytestring instead of request.POST
We can convert this bytestring into a JSON object or dictionary and then access the variables just like we access variables from any dictionary.




Form Data URL Encoded:

This body format is just like a form-data format with a minor difference. 

post request form url encoded


Equivalent CURL request code:

curl --location --request POST 'localhost:8000/post-example/form-urlencoded/' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'name=pythoncircle' \
--data-urlencode 'name_spaced=python circle' \
--data-urlencode 'url=https://www.pythoncircle.com'

Accessing request in view.py file:

@csrf_exempt
def post_example_form_urlencoded(request):
print('POST', request.POST)
print('BODY', request.body)
print(parse_qs(request.body.decode('utf-8')))
return render(request, 'hw/home.html', {})

The output of print statements:

POST <QueryDict: {'name': ['pythoncircle'], 'name_spaced': ['python circle'], 'url': ['https://www.pythoncircle.com']}>
BODY b'name=pythoncircle&name_spaced=python%20circle&url=https%3A%2F%2Fwww.pythoncircle.com'
{'name': ['pythoncircle'], 'name_spaced': ['python circle'], 'url': ['https://www.pythoncircle.com']}

As you can see, data is received in both request.POST as well as request.body attribute. Data in request.POST attribute is a QueryDict while in request.body is urlencoded bytestring.
We can decode the bytestring and then parse the urlencoded string using urllib.parse.parse_qs module.




Binary:

In this body format, file data is transferred in binary format.

post request binary data

The file name is helloworld.txt.

File content:

helloworld
next line
this is third line

Equivalent CURL request code:

curl --location --request POST 'localhost:8000/post-example/binary/' \
--header 'Content-Type: text/plain' \
--data-binary '@/home/rana/helloworld.txt'

Accessing request in view.py file:

@csrf_exempt
def post_example_binary(request):
print('POST', request.POST)
print('BODY', request.body)
return render(request, 'hw/home.html', {})

The output of print statements:

POST <QueryDict: {}>
BODY b'helloworld\nnext line\nthis is third line\n'

Data is received in request.body attribute in bytestring format with newline characters. Decode the bytestring and then split it using a newline character and access the one line at a time from array/list of strings.




Uploading file with form data:

This is the same body format as form-data. But in this request, we will send a file along with text key-values.

post request file upload


Equivalent CURL request code:

curl --location --request POST 'localhost:8000/post-example/file-upload/' \
--form 'file=@/home/rana/helloworld.txt' \
--form 'name=pythoncircle'

Accessing request in view.py file:

@csrf_exempt
def post_example_file_upload(request):
print('POST', request.POST)
print('FILES', request.FILES)
return render(request, 'hw/home.html', {})


The output of print statements:

POST <QueryDict: {'name': ['pythoncircle']}>
FILES <MultiValueDict: {'file': [<InMemoryUploadedFile: helloworld.txt (text/plain)>]}>

This is the first time we are access request.FILES attribute. Any file uploaded is available as InMemoryUploadedFile object in this attribute.




None body format:

In this format, the body is not sent in the post request.

no body


Equivalent CURL request code:

curl --location --request POST 'localhost:8000/post-example/none/'


Accessing request in view.py file:

@csrf_exempt
def post_example_none(request):
print('POST', request.POST)
print('BODY', request.body)
print('FILES', request.FILES)
return render(request, 'hw/home.html', {})


The output of print statements:

POST <QueryDict: {}>
BODY b''
FILES <MultiValueDict: {}>

Since the body is not sent with this post request, the value of attributes request.POST, request.body and request.FILES is empty.


The code used in this article is available on GitHub. Clone the repository, checkout the branch post_request_examples and set up the project as explained in READ.ME file.


Host your Django Application for free on PythonAnyWhere. If you want full control of your application and server, you should consider DigitalOcean. Create an account with this link and get $100 credits.





Cover Photo by Clément H on Unsplash
requests   0   16799

Related Articles:
Get latest Bitcoin and other crypto-currencies rates using python Django
Getting and displaying the latest bitcoin and other crypto currencies prices using python Django. Complete step to step guide to develop a django project to fetch bitcoin prices. Bitcoin prices in python....
Scraping data of 2019 Indian General Election using Python Request and BeautifulSoup and analyzing it
scraping 2019 election data india, Scraping data of 2019 Indian General Election using Python BeautifulSoup and analyzing it, using beautifulsoup to collection election data, using request...
Getting query params from request in Django
In this article, we will see how to access the query parameters from a request in the Django view, Accessing GET attribute of request, get() vs getlist() method of request in Django, query parameters Django,...
Python Requests Library: Sending HTTP GET and POST requests using Python
Python requests library to send GET and POST requests, Sending query params in Python Requests GET method, Sending JSON object using python requests POST method, checking response headers and response status in python requests library...

0 thoughts on 'Sending Post Request With Different Body Formats In Django'
Leave a comment:


*All Fields are mandatory. **Email Id will not be published publicly.

SUBSCRIBE
Please subscribe to get the latest articles in your mailbox.

© 2017-2020 Python Circle   Contact   Sponsor   Archive   Sitemap