Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve "Raw Data" empty json for POST?

The browsable django-reset-framework provides a convenient "Raw Data" tab that contains an empty-json, making it easy to create new objects.

I have many different Serializers that change per request type (GET/POST) and other logic, so I would like to test this empty-json as part of my unit-tests.

My question is: how to programmatically retrieve the serializer based on an APIClient request (drf's test-client)?

I see the code at https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/renderers.py#L454, specificaly,

view.get_serializer(instance=obj)

but I am still not able to construct a serializer from an APIClient.

like image 664
nak Avatar asked Apr 03 '14 09:04

nak


2 Answers

Building on blck's suggestion, I am using the OPTIONS to receive the json schema. Unfortunately, the DRF OPTION method had a problem: it creates a cloned-request to simulate PUT/POST methods, but did not propagate the cloned-request to the View. This caused views that change the serializer per the http-method to return the incorrect serializer.

For instance, my view uses one serializer for GET, and another for POST/PUT:

def get_serializer_class(self):
    return WriteSerializer if request.method in ['POST', 'PUT'] else ReadSerializer

I made a pull-request here: http://github.com/tomchristie/django-rest-framework/pull/1507

like image 193
nak Avatar answered Oct 14 '22 07:10

nak


Why would you want to retrieve the serializer with the client?? Usually the client has to know how to make each request (explained in the API documentation). You have to send the request and write the json format manually.

The browsable API knows how to represent the data because it is running in the server part.

Anyway, one thing you can try, is to request OPTIONS: curl -X OPTIONS url/object -u user:pass and parse the output (you have the fields definition in the response telling you which var type is each attribute and more. But, as I've said, this is not very common.

Hope it helps.

like image 39
argaen Avatar answered Oct 14 '22 07:10

argaen