Sorry for my poor language usage.
I am using drf for my web api. It has special renderers. I can use django views, or drf pure APIView. I can use TemplateHTMLRenderer which is good but all of them make drf not necessary. Because i want to use drf browsable api features. Using post, put, delete forms. Using json and html in api, less and clean code.
But the problem is, i cant customize browsable api, i cant send extra content or context. For example; i am using serializer for my Post model but also i need another query serializer too. Which they are not related actualy.
Too much talk. My question is; i want to customize browsable api with his features and with more extra data. But i could not see any documant for it.
Thanks.
This methods are sending data with content in response which is in json data.
https://github.com/encode/django-rest-framework/blob/master/rest_framework/renderers.py#L686-L722
like here. I can use content or view, or forms in my api.html and I want to add more data here. Like;
'mydata': Posts.objects.all(),
'mydata2': Blogs.objects.all(),
and after that, i want to use them in my api.html(or in custom template).
Related
I'm new to Python and I've seen a lot of tutorials which jump into the Django REST Framework when discussing how to create REST APIs without explaining why they need this library. I don't see the purpose of using the Django Rest Framework when I can just define API endpoints in views and return a simple HttpResponse to send data to a client.
What does the Django Rest Framework accomplish that I can't do simply using HttpResponse? Why is it worth learning?
I was going to use the library as it was included in the video, but it seemed more complex than I needed and I decided to try creating an API without Django REST Framework
def getStats(request):
print('--------STARTING Stats----------')
# Take some GET variable
version = request.GET.get('version')
# Get some data
with open('static/data.json') as f:
data = json.load(f)
# Filter the data
if version is not None:
data = list(filter(lambda x: x['version'] == version, data))
print("FILTERED DATA", len(data))
# Perform some operations on the data
data = calculateStats(data)
# Return an HTTP response
return HttpResponse(json.dumps(data))
This code seemed to work as needed and I get the feeling that I could make this view more robust if needed based on the demands of my application.
The DRF is a complete toolkit for building RESTful APIs in Django, including authentication, serialization, etc. You can do without it but, in the end of the day, the DRF will save you a lot of time.
It fits well with the Django architecture and it's also quite extensible, so you won't be locked-in to some obscure extension, as it happens sometimes.
Perhaps this old reddit post from Tom Christie (DRF's creator) can shed some more light:
Django REST framework isn't required, but it helps you get a lot of
things right that will be time consuming and error prone if you're
working from core Django.
Your example is very simple. When you have more complex logic with orm, permissions, serialization, and others. You will see the benefits of django restframework. You can build a crud very fast using viewsets that guarantee permissions, filters, with the REST API structure using POST, GET, PATCH, PUT, DELETE. You can list, create, update and delete. I recommend that you do the restframework tutorial https://www.django-rest-framework.org/tutorial/quickstart/ and it will become clear to you if is the right choice or not.
You can also use it for your example like this:
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
#api_view(['GET'])
def getStats(request):
print('--------STARTING Stats----------')
# Take some GET variable
version = request.GET.get('version')
# Get some data
with open('static/data.json') as f:
data = json.load(f)
# Filter the data
if version is not None:
data = list(filter(lambda x: x['version'] == version, data))
print("FILTERED DATA", len(data))
# Perform some operations on the data
data = calculateStats(data)
# Return an HTTP response
return Response(json.dumps(data, status=status.HTTP_200_OK)
Django REST framework offers a bunch of useful features over raw Django:
Serializers that convert between representations (dictionaries, JSON, etc.) and model instances.
Generic class-based views that let you build CRUD APIs with minimal code.
A flexible request parsing system that handles complex request datatypes, like JSON and multipart file uploads.
Customizable request authentication and permissions.
Throttling to control rate limiting.
Filtering and ordering of queryset results.
Response pagination.
API documentation with schema generation.
Content negotiation to support multiple response types (JSON, XML, etc.)
And much more!
In short, Django REST framework handles a lot of the boilerplate and complexity of building an API, allowing you to focus on your application's logic.
So I'm trying to setup my Django view such that when they POST to an endpoint they don't need an url parameters, but when they call GET they require it
path('posts/', views.PostView.as_view(), name="post"),
path('posts/<int:count>/', views.PostView.as_view(), name="post"),
The issue with this is that it makes swagger messy and swagger with assume that url/posts/ you can POST and GET from, and url/posts// you can as well, but I only want to be able to POST to the first and GET from the 2nd. Is there a way to do this without creating separate view classes for them? Or is it better practice in this case to create separate view classes?
This may be an opinionated question but sorry I am too curious.
I learned to develop Django Model-View-Template websites ( multi page websites) and Django Rest Framework.
From the same Django Model can I create Rest API's and MVC templates together ?
I wanted to develop a Blog website that use session authentication and based on MVC architecture. The same server should create API's because the Mobile app for the Blog may consume the API's and use Token Authentication (using Djoser).
If I use same User model for session and token authentication, Can mobile blog app users use their username and password to access website version ?
Django REST Framework is just a collection of helpers to easily create HTTP endpoints that conform to REST behaviour, which mostly means conventions around GET, POST, PUT and DELETE. You could code all this behaviour by hand using default Django, DRF just makes it a lot easier. The end result are simply specific routes which accept input and return output in specific formats to/from models.
Of course you can use that in addition to normal Django Views. It's just a different interface to your models and other business logic. Authentication can be the same, but typically you use some sort of token authentication for the API; that ultimately depends on how the API is supposed to be used exactly.
I would like to know if it is possible to build a REST Api using only Django (without Django REST).
I have following code in my views.py my Django (no REST Django)
from django.http import HttpResponse, JsonResponse
def get_something(request, object = None):
dummyDict = {'Debug':object}
return JsonResponse(dummyDict)
ulrs.py
url(r'^(?P<object>\w{1,50})$', views.get-something, name = "get-something"),
Can this work as REST API?
I tried testing using curl and I get following answer from my django server:
HTTP/1.0 200 OK
Date:
Server:
X-Frame-Options:
Content-Type: application/json
{"Debug": daodoaw}
You may do that though you'll have to add a lot of things to make an API RESTfull.
Your example is already missing proper response code for PUT / POST / PATCH / DELETE and doesn't respond correctly to OPTIONS
Ofcourse you can do these things with Django, but the advantage of django rest is that it is specifically created to handle api creation and management, Thus using django rest will be much more effective. When you look at the documentation of django rest, you could see that viewsets like ModelViewSet, GenericViewSet which are capable of handling any type of requests(POST, PUT, PATCH, etc...) in a two or three line code. Meanwhile while you using django you have to specify each and every case. Its just a case where DRF is more preferred).
What I try to say is, DRF is more handy in the case of API Creation and has a very good documentation in their official website
If you have to know about any specific part, please comment below
Thanks
Using Django is not a crime! We are given the liberty to use either DRFor Django.
Here are some of the situations when you can think of using DRF:
Let's imagine, you have developed a web application with django. What would happen if your client or you want a mobile version (android/iOS version) of your application? As multi-platform development is becoming the norm, using DRF can become crucial to reuse the same backend for both a mobile app and a web app.
Another comprehensive reason to use DRF is its super easy serialization facility.
If you want to segregate your front-end from Django provided templates, you are free to use modern javascript frameworks such as Vue, React or Angular for better design and to be dynamic as much as possible with your REST APIs.
When you use DRF, you are given ready-made view classes (ApiView, GenericAPIView, Viewsets) that are only a few lines of coding and able to handle all sorts of requests such as (POST, PUT, PATCH, etc...).
NOTE: Definitely, you can use Django depending on the project you are handling. In the case of building a web application that doesn't need to be accessed from other platforms, I would not use DRF. It entirely depends on the requirements.
I want to use Django REST framework for my new project but I am not sure if I can do it efficiently. I would like to be able to integrate easily classical Django app in my API. However I don't know how I can proceed to make them respect the REST framework philosophy. Will I have to rewrite all the views or is there a more suitable solution?
"Normal" Django views (usually) return HTML pages.
Django-Rest-Framework views (usually) return JSON.
I am assuming you are looking for something more like a Single page application.
In this case you will have a main view that will be the bulk of the HTML page. This will be served from "standard" Django view returning HTML (which will likely include a fair bit of JavaScript).
Once the page is loaded the JavaScript code will makes requests to the DRF views. So when you interact with the page, JavaScript will request Json, and update (not reload) the page based on the contents of the JSON.
Does that make sense?