Reputation: 1659
Currently I am having a requirement for a Django project, in which I need to develop django API without using any API frameworks. So inorder to proceed I would like to know how can I do creation of API without third party frameworks.
Upvotes: 2
Views: 2210
Reputation: 19816
You can use JsonResponse
to return json data in your views:
from django.http import JsonResponse
def my_view(request):
questions = Question.objects.all()
return JsonResponse({'questions': questions})
Upvotes: 5
Reputation: 2112
You can use regular function-based or class-based views as your endpoints. The difference would be is that you'll probably be sending JSON instead of rendering HTML in the response.
You can use built in decorators from Django to restrict certain access (ie. methods, permissions, etc.)
My code would look something like:
View
@require_get
@login_required
def get_user(request, userId, *args, **kwargs):
user = get_object_or_404(User, pk=userId)
serializer = SomeSerializerClass(user)
return HttpResponse(serializer.jsonData(), content_type='application/json')
Url
url('/user/(?P<userId>[0-9]+)/$', get_user, ...)
Upvotes: 5