Building REST API With Django Rest Framework
In this tutorial, we are going to learn about creating REST API in Django. Before going on the ground of coding, let us first learn a bit about REST API.
What actually is REST API?
API stands for Application Programming Interface which is a software intermediary that allows two software programs to connect and talk to each other.
REST stands for REpresentational State Transfer. REST is simply an architectural style on how an API should behave and look. So whenever we call a REST or RESTful API, the server provides us or the client with the representation of the state of the requested resources.
There are a few request option that REST API provides us :
- GET — According to the endpoints and parameters that we pass, the API returns some data.
- PUT — It looks for the record in the provided URI and updates the existing record. If the record is not present, it creates a new one.
- POST — It creates and adds a new record in the database.
- DELETE — It removes the requested record in the given URI.
- PATCH — It updates the individual fields of a record.
Now let’s fold up our sleeves and get started to build a REST API with Django Rest Framework.
1. DJANGO CONFIGURATION
I generally use pip and pipenv for setting up the environment for Django. You can choose your own tools as well.
If you have not already installed
pipenv on your machine you can do it by:
$ pip install pipenv
1.1 Install Django and Configure Virtual Environment
$ pipenv install django
Next, let us activate the environment
$ pipenv shell
and then create a new django project
$ django-admin startproject myrestapi
Now our directory will look like
myrestapi/ Pipfile Pipfile.lock
Again if we look into the myrestapi folder.
$ cd myrestapi
Test the project with the Django server and make sure it works up to now.
$ python manage.py runserverWatching for file changes with StatReloaderPerforming system checks…System check identified no issues (0 silenced).
You have 18 unapplied migration(s).
Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.November 27, 2020–06:46:53Django version 3.1.3, using settings 'myrestapi.settings'Starting development server at
Quit the server with CONTROL-C.
Now Goto http://127.0.0.1:8000/ and check out the warm welcoming page from Django.
1.2 Create API app
Let us create a new separate app for API
$ python manage.py startapp api
api db.sqlite3 manage.py myrestapi/
1.3 Register the api app with the myrestapi project
First and foremost thing to do after we create an app in django project is to register it in the project level settings file.
Let us register it now in myrestapi/settings.py file
1.4 Migrate the Database
Django ORM creates a sql commands for us whenever we create a new models in our project. But before making any new models, we need to migrate it because django project itself comes with some cool models built-in beforehand.
So let us migrate them now.
$ python manage.py migrateOperations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: Applying contenttypes.0001_initial… OK
Applying auth.0001_initial… OK
Applying admin.0001_initial… OK
Applying admin.0002_logentry_remove_auto_add… OK
Applying admin.0003_logentry_add_action_flag_choices… OK
Applying contenttypes.0002_remove_content_type_name… OK
Applying auth.0002_alter_permission_name_max_length… OK
Applying auth.0003_alter_user_email_max_length… OK
Applying auth.0004_alter_user_username_opts… OK
Applying auth.0005_alter_user_last_login_null… OK
Applying auth.0006_require_contenttypes_0002… OK
Applying auth.0007_alter_validators_add_error_messages… OK
Applying auth.0008_alter_user_username_max_length… OK
Applying auth.0009_alter_user_last_name_max_length… OK
Applying auth.0010_alter_group_name_max_length… OK
Applying auth.0011_update_proxy_permissions… OK
Applying auth.0012_alter_user_first_name_max_length… OK
Applying sessions.0001_initial… OK
1.5 Create a Superuser
Before going any further let us create a superuser which will allows us to check out out models in the cool built-in admin interface. Isn’t it great?
$ python manage.py createsuperuserUsername (leave blank to use 'navraj'):
Password (again): This password is too common. Bypass password validation and create user anyway? [y/N]: y Superuser created successfully.
Start the django server to verify the credentials.
$ python manage.py runserver
Head over to the http://127.0.0.1:8000/admin/
Now login with the credentials created before and you will be able to see :
See those groups and users model that we were talking about before.
2. Create a model in the api app
Now create our first model.
Open up the file api/models.py
name and location are the strings which is in the form of CharField. And the __str__ method returns instance of the model Detective, in this case a name and we can put anyother fields as per the requirement.
2.2 Make migrations
We just created a new model. Whenever we update existing model or create a new one, we need to make the migrations so that django will make the necessary commands.
$ python manage.py makemigrationsMigrations for 'api': api/migrations/0001_initial.py
- Create model Detective$ python manage.py migrateOperations to perform: Apply all migrations: admin, api, auth, contenttypes, sessions Running migrations: Applying api.0001_initial… OK
2.3 Register Detective in the admin site
Shortly before we saw the cool django admin page. But it will not show our newly created model. So let us add two lines of code in api/admin.py file.
Now run the django server and goto http://127.0.0.1:8000/admin/
2.4 Create some cool Detectives
Let us create some new detectives in the admin page. Click on “Add” and you are ready to go.
Look at those classy detectives
3. Set up Django Rest Framework
Let us install Django Rest Framework so that we can serialize our records in the databases.
$ pipenv install djangorestframework
Again register the newly installed app in the myrestapi/settings.py file.
Its good to comment out for clarity!
4. Now Serialize the Detective Model
Serialization is the process of converting database records into the JSON formatted values so that API user can understand them. Similarly if we provide the JSON value as a request, it should be converted as the model database value so that django can save them.
This all will be handled by rest framework. All we need to do is some configuration work. We have to connect the Django Rest framework and the models that we created before.
Create a new file as serializers.py in the api/ directory
5. View the Data
Now all left is to display the data in the browser. For that we have to some configuration urls and views file.
Head over to the api/views.py file and edit it as:
5.2 Project Level URLs
We have to specify the url at the project level file at first. Django looks up to site urls at first to resolve the requested url address.
Head over to the file myrestapi/urls.py
5.3 App-Level URLs
We just added some codes but let us take some time to comprehend it. We included api.urls in the project level urls file. But wait..Where is that file? We have to create that now in the app level directory which in case of our project is api.
Create a new file name as urls.py inside the app/ directory and edit it as :
So our work is finished here. But wait we have to understand what’s going on here? See the routers we have imported. Django Rest Framework router helps to dynamically link the request with the corresponding resources.
Now Enjoy the testing
Start up the django server again and head over to http://127.0.0.1:8000/
See those Beautiful design just for an API !
This is the root page for our APIs. Now click on the link or head over to this link http://127.0.0.1:8000/detectives/
Get The Individual Detectives With IDs
We can also get the individual detective api with the format
http://127.0.0.1:8000/detectives/<id> where id is the unique key for our detectives which is automatically assigned by django models.
We can also display the id of the detectives with a small tweak in our api/serializers.py file by including id in the fields as:
After that we can see the API List as :
Add a new detective Via POST Request
Add a new detective with post request as:
Mr. L is now added to the list of detectives in our API.
This is all about this tutorial.
You can check out your code in this github source code too : https://github.com/NavTheRaj/djangorest_tutorial.git.