2

I'm building a simple API and I'm trying to test POST request. Post request should create a new record based on only one param: title.

I'm using manage.py test for testing and I've set up the client:

client = rest_framework.test.APIClient()

Problem: it works fine when I'm giving the URL manually ("snatch" is a title of a movie).

response = client.post('/movies/?title=snatch', format='json')

In this case I can access the title in my view request.query_params.get('title') and request.data.get('title').

But when I'm trying to pass the title in data argument:

response = client.post('/movies/', data={'title':'snatch'}, format='json')

This should access '/movies/?title=snatch', but instead accesses only '/movies/'. I can access the title through request.data.get('title'), but not through request.query_params.get('title').

How should I access the params sent in POST request? Is accessing through request.data a correct way? Can someone give me a better explanation of the differences and use cases?

MKaras
  • 665
  • 7
  • 17
  • 1
    [https://stackoverflow.com/questions/611906/http-post-with-url-query-parameters-good-idea-or-not](https://stackoverflow.com/questions/611906/http-post-with-url-query-parameters-good-idea-or-not) – Waket Zheng Mar 14 '19 at 08:35
  • Thanks, included the link in the accepted answer. – MKaras Mar 14 '19 at 10:35

1 Answers1

4

request.data hold the data sent in request body, i.e with the data parameter here:

response = client.post('/movies/', data={'title':'snatch'}, format='json')

request.query_params hold the data sent in query string parameters, i.e title here:

response = client.post('/movies/?title=snatch', format='json')

To exepmlyfy, if you send such a request:

response = client.post('/movies/?director=guyritchie', data={'title':'snatch'}, format='json')

you can get director parameter through request.query_params, and title parameter through request.data

More on difference between data and query_params: HTTP POST with URL query parameters -- good idea or not?

MKaras
  • 665
  • 7
  • 17
Ozgur Akcali
  • 5,264
  • 2
  • 31
  • 49
  • Thanks, this was helpful. I edited the answer the include a link from Waket Zheng, as it also helped me to understand the issue. – MKaras Mar 14 '19 at 10:34