I'm django 1.11.7 with rest framework. I've been trying to access POST request headers but when I print it I get 'None'. I'm sending a request using the application postman. I've added a key-value pair in the Headers section and the request code looks like this:
POST /create_user HTTP/1.1
Host: localhost:8000
Content-Type: application/json
key1: value1
Cache-Control: no-cache
Postman-Token: # Postman token
{
"username": "abcdefgh@123"
}
In my django app, my views.py file looks like this:
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
import json
# Create your views here.
class CreateUser(APIView):
def post(self, request, format='json'):
try:
request_data = json.loads(request.body.decode(encoding='UTF-8'))
print 'Header data:', request.POST.get('key1')
The 'request' variable is of type Request (Django Rest Framework object). There is no exception raised. So how do I access the POST 'key1' header?
request.META. It is a dictionary containing all available HTTP headers.request.META['KEY1']work?. Because as per the django documentation "any HTTP headers in the request are converted to META keys by converting all characters to uppercase, replacing any hyphens with underscores and adding an HTTP_ prefix to the name"'HTTP_KEY1'. Typo. Here's a fixed version of my original comment:request.POSTcontains POST data, not headers. Tryrequest.META['HTTP_KEY1'].