Documenting a DRF GET endpoint with multiple responses using Swagger - django

I have a GET endpoint for a RESTful API I am creating using Django.
This endpoint reads three values from the URL's query string. A particular parameter in the query string has the potential to change the data (include extra fields and change the structure slightly) which is returned in the JSON response from this endpoint.
This endpoint is not tied directly to a single model. My view subclasses RetrieveAPIView, in the view, I override the get_object method and some logic is performed to query multiple models, make some decisions and return an ordered dictionary.
My problem is as follows:
I would like to document this endpoint using Swagger. I am using drf-yasg to generate my Swagger documentation. I have no serializers declared for this view; since I manually construct an ordered dictionary in get_object I don't see the purpose of declaring one. I'm not sure how to document my endpoint using drf-yasg.
I have discovered only one approach to document the endpoint, but it is quite ugly and bloats my code, and I'm wondering if there is a better approach.
By declaring an openapi.Response object, and supplying this object to the #swagger_auto_schema decorator Swagger displays the two possible responses, but describing the entire response really bloats my code. Here is an example if what currently works to document the endpoint:
class View(RetrieveAPIView):
http_method_names = ['get']
response_json = {
'Response if X query parameter is something': {
'key1': 'string',
'key3': {
'key4': 0,
'key5': 'string',
'key6': 'string'
}
},
'Response if X query parameter is something else': {
'key1': 'string',
'key2': 'string'
}
}
swagger_get_responses = openapi.Response(description='Description for the set of responses',
examples=response_json)
#swagger_auto_schema(responses={200: swagger_get_responses})
def get(self, request, *args, **kwargs):
return super().get(request, args, kwargs)
def get_object(self):
// Execute a method on a model that queries other models, performs some logic, and
// then returns an ordered dict which is then returned by this function.
Is there a better approach to this problem? Is there a better Django design pattern/feature of the Django framework or drf-yasg library that I can apply here that will help me handle multiple response bodies?

Related

Nest model serializers in Django without using rest framework

I would like to know if it's possible to nest serializers without using the rest framework.
I was reading this question and I would like to do something similar but I am not allowed to use the rest framework.
Is it possible to serialize models with foreign keys using a similar approach (nesting) without using the rest framework?
At the moment I am serializing json like this:
data = serialize("json", myModelObject, fields=('id', 'foreignKeyField'), cls=DatetimeJSONEncoder)
And I would like to do something like this:
data = serialize("json", myModelObject, fields=('id', 'foreignKeyField.some_value'), cls=DatetimeJSONEncoder)
first make sure your view inherit from JSONResponseMixin
class JSONResponseMixin(object):
def render_to_json_response(self, context, **response_kwargs):
return JsonResponse(self.get_data(context), **response_kwargs)
def get_data(self, context):
return context
how about this :
Broaden your query values to include foreignKeyField.some_value
convert the queryset to list
return the json list as response for your ajax request
access your response as json array in ajax success
results = MyModel.objects.filte(my_filter).values("field_1",
"field_2",
"field_n",
"foreignKeyfield__field_11",
"foreignKeyfield__field_22")
results_list = json.dumps(results)
return JsonResponse(results_list)
it depends on your frontend technologie , try to output the reponse and parse with joy
let me know in the comments section if you need more details

Django Rest Framework: Without Model

I'm working on creating a RESTAPI using DRF(Django Rest Framework). API just receives the users twitter handle and returns his twitter data.
Here, I'm not using model here because it's not required.
Should I use a serializer here? If so why? Now I'm able to return the data without using a serializer.
Moreover, My API is not web-browsable. How should I make it web-browsable: which is one of the best features of DRF.
Edit:1
I'm using Functions in Views.
#api_view(['GET'])
#csrf_exempt
def getdetails(request):
call the twitter api
receive the data
return HttpResponse(JsonResponse( {'data': {'twitter_id':id,'tweets':count,'Followers':followers,'following':count_follow}}))
In the browser I'm just seeing JSON data like this.
{"data": {"twitter_id": 352525, "tweets": 121, "Followers": 1008, "following": 281}}
You can use Serializer for the result
class SampleSerializer(serializers.Serializer):
field1 = serializers.CharField()
field2 = serializers.IntegerField()
# ... other fields
Usage
my_data = {
"field1": "my sample",
"field2": 123456
}
my_serializer = SampleSerializer(data=my_data)
my_serializer.is_valid(True)
data = my_serializer.data
You'll get serialized data in data variable (you can use my_serializer.data directly)
Should I use a serializer here?
It's up to you, because if you wish to show the response JSON without any modification from the Twitter API, you can go without DRF serializer. And If you wish to do some formatting on the JSON, my answer will help you
My API is not web-browsable. How should I make it web-browsable?
Maybe you followed wrong procedure. Anyway we can't say more on this thing without seeing your code snippets
Update-1
from rest_framework.response import Response
#api_view(['GET'])
#csrf_exempt
def getdetails(request):
call the twitter api
twitter_api = get_response_from_twitter() # Json response
return Response(data=twitter_api)

Using Django Rest Framework, is it possible to get results internally on server within Django?

I have a complex DRF ViewSet that supports paging, filtering, sorting, etc. that backends a grid view. To build an "export" capability, I need to be able to take the same querystring that my endpoint uses, such as:
?obj_id=129&ordering=latitude&city__icontains=nap
And be able to, in Django, send that string into DRF somehow and get the fully-modified queryset after all the view's filters, sorts, etc are applied (the same way as the GET did). I could use the fully-rendered json response or some interim filter-applied queryset. Is it possible to use DRF in this way?
You should write a CSV renderer for your viewset and get that content-type to export the CSV.
There's even one already available.
Yes you could, if you already have a request object i.e. If you want to use this DRF viewset into another view which has the request object:
def another_view(request):
# make a copy of the `GET` attribute of request object
request.GET = request.GET.copy()
# now you can set the query params on this GET object
# ?obj_id=129&ordering=latitude&city__icontains=nap
request.GET['obj_id'] = 129
request.GET['ordering'] = 'latitude'
request.GET['city__icontains'] = 'nap'
# you can also set paging options in similar way
# now instantiate the viewset
vs = DRFViewset.as_view()
# call the view for response
# set kwargs as you need
response = vs(request, *args, **kwargs)
# response.data will have what you want here

django rest post return 405 error code

I am using django with rest framework and I try to test POST on existing object but I keep getting 405. my ViewSet looks like this:
class Agents(viewsets.ModelViewSet):
serializer_class = serializer.AgentSerializer
model = serializer_class.Meta.model
....
and in the urls:
router = routers.SimpleRouter()
router.register(r'rest/agents', api_views.Agents, "Agent")
...
urlpatterns += router.urls
I call the post request from within APITestCase class (rest testing), my post request looks like this:
response = self.client.post(url, {'available': True, 'online':True}, format='json')
and printing url shows "/chat/rest/agents/1910_1567/", while 1910_1567 is the valid id of an existing agent (I create the agent during the setup and use its id).
I've seen other questions about rest post getting 405, but all the solutions there were url-related and in my case the url is correct. I even ran the setup outside the test and accessed the url via browser to get the object and the object indeed exist. but when I try to post to it - 405.
any ideas?
thanks!
Most probably your url is somehow matching with some different url's regex, and the request is being dispatched to some other view which disallows post request. Could you mention others urls in your urls.py? Infact you can verify this by adding pdb(debugger) in dispatch method of your view. If you made it to the pdb, then you can assume I was wrong.
If that is not the case, then you can evaluate the issue from dispatch method with debugger. Just in case you have any doubt about how to do that -
class Agents(viewsets.ModelViewSet):
serializer_class = serializer.AgentSerializer
model = serializer_class.Meta.model
def dispatch(self, *args, **kwargs):
import ipdb; ipdb.set_trace()
return super(Agents, self).dispatch(*args, **kwargs)
Solution Found:-
You are passing id in url, so this request would be routed to detail view and detail view only allow GET, PUT, DELETE operations on resource since resource already exists. So to create resource, don't provide the id. Otherwise use PUT request and provide support for creation in PUT.
POST are supposed to be for creation purpose. If you want to update with a ViewSet you'll need to PUT or PATCH (partial update) instead.
Edit:
For more about this, here's some explanation on the HTTP methods used for REST API:
http://restful-api-design.readthedocs.org/en/latest/methods.html
This is also described in the DRF documentation at:
http://www.django-rest-framework.org/api-guide/routers/#simplerouter

Django REST framework: non-model serializer

I am beginner in Django REST framework and need your advice. I am developing a web service. The service has to provide REST interface to other services. The REST interface, which I need to implement, is not working with my models directly (I mean the get, put, post, delete operations). Instead, it provides other services with some calculation results. On a request my service makes some calculations and just returns the results back (doesn't store the results in its own database).
Below is my understanding of how that REST interface could be implemented. Correct me, if I am wrong.
Create class which makes the calculations. Name it 'CalcClass'. CalcClass uses the models in its work.
Params necessary for the calculations are passed to the constructor.
Implement the calc operation. It returns results as 'ResultClass'.
Create ResultClass.
Derived from object.
It just only has attributes containing the calc results.
One part of the calc results is represented as tuple of tuples. As I understand, it would be better for further serialization to implement a separate class for those results and add list of such objects to ResultClass.
Create Serializer for ResultClass.
Derive from serializers.Serializer.
The calc results are read-only, so use mostly Field class for fields, instead of specialized classes, such as IntegerField.
I should not impl save() method neither on ResultClass, nor on Serializer, because I am not going to store the results (I just want to return them on request).
Impl serializer for nested results (remember tuple of tuples mentioned above).
Create View to return calculation results.
Derive from APIView.
Need just get().
In get() create CalcClass with params retrieved from the request, call its calc(), get ResultClass, create Serializer and pass the ResultClass to it, return Response(serializer.data).
URLs
There is no api root in my case. I should just have URLs to get various calc results (calc with diff params).
Add calling format_suffix_patterns for api browsing.
Did I miss something? Is the approach is correct in general?
Django-rest-framework works well even without tying it to a model. Your approach sounds ok, but I believe you can trim some of the steps to get everything working.
For example, rest framework comes with a few built-in renderers. Out of the box it can return JSON and XML to the API consumer. You can also enable YAML by just installing the required python module. Django-rest-framework will output any basic object like dict, list and tuple without any extra work on your part.
So basically you only have to create the function or class that takes in arguments, does all of the required calculations and returns its results in a tuple to the REST api view. If JSON and/or XML fits your needs, django-rest-framework will take care of the serialization for you.
You can skip steps 2 and 3 in this case, and just use one class for calculations and one for presentation to the API consumer.
Here are a few snippets may help you out:
Please note that I have not tested this. It's only meant as an example, but it should work :)
The CalcClass:
class CalcClass(object):
def __init__(self, *args, **kw):
# Initialize any variables you need from the input you get
pass
def do_work(self):
# Do some calculations here
# returns a tuple ((1,2,3, ), (4,5,6,))
result = ((1,2,3, ), (4,5,6,)) # final result
return result
The REST view:
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from MyProject.MyApp import CalcClass
class MyRESTView(APIView):
def get(self, request, *args, **kw):
# Process any get params that you may need
# If you don't need to process get params,
# you can skip this part
get_arg1 = request.GET.get('arg1', None)
get_arg2 = request.GET.get('arg2', None)
# Any URL parameters get passed in **kw
myClass = CalcClass(get_arg1, get_arg2, *args, **kw)
result = myClass.do_work()
response = Response(result, status=status.HTTP_200_OK)
return response
Your urls.py:
from MyProject.MyApp.views import MyRESTView
from django.conf.urls.defaults import *
urlpatterns = patterns('',
# this URL passes resource_id in **kw to MyRESTView
url(r'^api/v1.0/resource/(?P<resource_id>\d+)[/]?$', login_required(MyRESTView.as_view()), name='my_rest_view'),
url(r'^api/v1.0/resource[/]?$', login_required(MyRESTView.as_view()), name='my_rest_view'),
)
This code should output a list of lists when you access http://example.com/api/v1.0/resource/?format=json. If using a suffix, you can substitute ?format=json with .json. You may also specify the encoding you wish to get back by adding "Content-type" or "Accept" to the headers.
[
[
1,
2,
3
],
[
4,
5,
6
]
]