Function Views Basics

We need to define a couple things to make a function view. The first thing being a function. This will be a regular Python function with one parameter named request which looks like this:

def hello_world(request):
# logic goes here
pass
from rest_framework.decorators import api_view
from rest_framework.response import Response
@api_view([‘GET’, ‘POST’])
def hello_world(request):
return Response({‘message’: ‘hello world’})

How to Handle Post Requests

In the above example we have the same logic for both post and get requests. Most likely you will want separate things to happen for each request. Luckily the request object that we passed into our function can help us with this. Take a look at the example below:

from rest_framework.decorators import api_view
from rest_framework.response import Response
@api_view(['GET', 'POST'])
def hello_world(request):
if request.method == 'POST':
return Response({'message': 'Got some data: ' + str(request.data)})
return Response({'message': 'hello world'})

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store