How to build REST API using Django and Django REST Framework
This week is MeetU first iteration in this sprint, I got a job to designing database for the application, but I think designing the database shouldn’t take too long, and I want my teammates to be able to test his/her application with real API and data.
So I started searching for the best (read: easiest) web framework available on the Internet and I found this thing called Django and the package for build REST API on top of Django application, Django REST Framework. After learning it for around 5 hours and 5 minutes. I started to build our backend infrastructure on top of it. So let’s get started!
Setup
First, we need to install Django and Django REST Framework via pip
pip install django djangorestframework
Second, we can init our project via django-admin command
django-admin startproject demo
Third, we can build post application which contains models, views, other things that we need to build our first apps.
python manage.py startapp post
Finally, we must register post app to our project, by adding post
in INSTALLED_APPS
in settings.py
# settings.py
...INSTALLED_APPS = [
...
'post',
...
]
And we’re good to go!
Model, View, Serializer
Like other web frameworks, Django uses an architecture similar to MVC (Model, View, Controller), in this case, MVT (Model, View, Template). So, the different between MVT and MVC are View in MVC handle how we’re displaying the data to the user, but View in MVT is the controller (logic) of the application) and Template in MVT handling the UI in MVT architecture, similar to View in MVC.
In our case, we’ll remove Template part since we’ve no UI and change View part with View from Django REST Framework, for serving our REST API.
First, build our simple model
And make migration file
python manage.py makemigrations
Also, don’t forget to migrate the databases
python manage.py migrate
Next, we build our serializer which allow complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered into JSON
, XML
or other content types. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.
After that, we can create our views using generics API that DRF provided, it provides basic GET and POST operations for our API
Finally, we can add this view to our urls so Django can handle request for particular URL with particular view
And it’s done! You can test it in your browser by looking at localhost:8000/posts/
after running your server with python manage.py runserver.
Ricky Putra Nursalim,
Software Engineer at MeetU