victortv
victortv

Reputation: 8942

Django Can't load Json in POST request body if more than 1 parameter is passed in URL

I have a views.py with an endpoint like this:

def endpoint(request):
    if request.method == "POST":
        body = request.body.decode('utf-8')
        body = json.loads(body)
        param1 = request.GET.get('param1','default1')
        param2 = request.GET.get('param2','default2')

My urls.py have this urlpattern:

url(r'^endpoint$', views.endpoint, name="endpoint")

The problem I have is that if I send requests in one of the following ways it works fine:

curl -X POST http://localhost:8000/endpoint -d @data.json

curl -X POST http://localhost:8000/endpoint?param1=val1 -d @data.json

curl -X POST http://localhost:8000/endpoint?param2=val2 -d @data.json

But if I send a request with both parameters:

curl -X POST http://localhost:8000/endpoint?param1=val1&param2=val2 -d @data.json

I get the exception:

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Why I get JSONDecodeError when having multiple parameters? Is it because it's a POST request?

EDIT: I have to use a file data.json because de body of the request is quite big.

I also tried with a smaller json

curl -X POST http://localhost:8000/endpoint?param1=val1&param2=val2 -d "{"a": "b"}"

To debug I inserted this on the beginning of the code:

print("request body:")
print(request.body)

I get this in the terminal:

request body: b''

It seems Django don't even receive the request body

Upvotes: 0

Views: 146

Answers (1)

user8060120
user8060120

Reputation:

in the command line the & means run command in background, try to put url in the double quotes: "http://localhost:8000/endpoint?param1=val1&param2=val2"

curl -X POST "http://localhost:8000/endpoint?param1=val1&param2=val2" -d @data.json

Upvotes: 2

Related Questions