0

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?

  • @Shamail Mulla Could you please try to print out `request.META` . It is a dictionary containing all available HTTP headers. – Abdul Niyas P M Nov 14 '17 at 08:36
  • 1
    @Blurp Does `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" – Abdul Niyas P M Nov 14 '17 at 08:44
  • 1
    @ABDULNIYASPM Yes, it should be `'HTTP_KEY1'`. Typo. Here's a fixed version of my original comment: `request.POST` contains POST data, not headers. Try `request.META['HTTP_KEY1']`. –  Nov 14 '17 at 08:46
  • @ABDULNIYASPM i kept trying key1.. but yes http_key1 worked.. Thanks! – Shamail Mulla Nov 14 '17 at 09:24

0 Answers0