Reputation: 727
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?
Upvotes: 2
Views: 3346
Reputation: 5492
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?
Upvotes: 4