Create a REST API With Django REST Framework

If you’ve used a digital device to send and receive information, you’ve used an API. Developers create APIs to enable users to interact with data from their applications.

Creating a REST API is a convenient way to share information. REST APIs have defined standards regulating data sharing between devices. To understand how REST APIs work, you’re able to build one from scratch.

4

You can use the Django REST framework to build a REST API and use it to display data from a database.

Using Django With a REST API

You canuse a REST API to fetch structured dataover HTTP. Like many languages and frameworks, Django lets you build your own API and consume others.

You should also have the following pre-installed:

The word “API” surrounded by abstract icons

Once you’ve installed all the essential software, you’re ready to begin.

1. Install Django REST Framework

Django REST frameworkis a powerful toolkit you can use to build and configure web APIs. Its customizable features make it a popular choice to build REST APIs.

you may install the Django REST framework with the following command:

Image shows successfully applied model migrations into database

2. Create a Django App

The following instructions will explain how to create a food application to gather names and descriptions of popular Kenyan foods. The API will fetch requests from a database to enable users to interact with that data.

Django apps come equipped with an SQLitedatabase, so you don’t have to install another database.

Image shows the Django admin login page

To create a Django app, first create a project calledfoodwith the following command:

Next, create a Django app calledkenyanfood:

Image shows Django-admin-interface with App models

3. Register the App Project Settings

Register thekenyanfoodapp in the project settings under theINSTALLED APPSarray. If you skip this step, Django will not recognize the app. Also, register the Django REST framework in the same settings:

4. Register App URLs

Registerkenyanfoodapp URLs in the projecturls.pyfile as illustrated below:

5. Create a View for the API

Create a dummy view in the app’sviews.pyfile, so the app does not throw errors. First, import theResponseobjectand@apiviewdecorator from the Django REST framework.

Responsehelps return sterilized data inJSONformat while the@apiviewdisplays the API.

6. Create a URL Path for the App

Create a URL path for the API view you created. This endpoint displays thekenyanfooddata.

7. Create a Model for the App

The app’s model class is calledFood.It should look like this:

Register the model in the appadmin.pyfile as shown below:

8. Make Migrations

Next,migratethe app to create tables in theSQLitedatabase. You can do this using the following command:

Next, apply these migrations by running this command:

A successful migration will look like this:

Successful migrations mean that the database has created tables for thekenyanfoodApp.

9. Add Data to the Database

Use theDjango adminGUI to enter data into the database.Django adminhas a great interface to visualize and manage your application’s data.

Alternatively, you can use the python shell on the command line to enter data manually into the database. In this guide, you will use the Django admin interface.

Use the following command to set up Django admin:

When prompted, enter yourusername, email, and password. you could then open the admin page using the link below:

You will see the login page:

Once you log in, you will see the Django administration interface withGroupsandUsersmodel. These are both for authentication; theFoodmodel is in the section below.

you could add and deleteFooditems from the database from the admin page. Add some Kenyan delicacies, such as Ugali, Pilau, and Chai, to the database.

Now that the database has data, create the API

10. Serialize the Model

Serializersconvert complex Django models toJSONobjects, making data easily read on the API. Serializing makes data more readable on the API.

Create a new file in the app calledserializer.py

You import theserializersmodule from therest_frameworkpackage and create aFoodSerializerclass that inherits from theModelSerializerclass.

Next, specify theFoodmodel you want to serialize and the fields you want to add to the API.

11. Update the View

Next, update the API view with theserializerandFoodmodels.

First, define aGETmethod to retrieve all the data from the database withFood.Objects.all()function. Then serialize the dataand returned it as a response inJSONformat.

Then, navigate to the server URL link:

You will see the API displaying data from the database:

Congratulations, you have created a REST API!

12. Add Data With POST Method

Test whether you can use the REST API to add data to the database.

First, define aPOSTmethod in the view.

Then, add a path in the appurls.pyto create an endpoint for the APIPOSTfunctionality.

Next, navigate tothis URL:

You will see thePOSTendpoint. Add data to the database inJSONformat in theContentsection and click thePOSTbutton. For example, add a new food item with this structure:

You will see the data displayed in red inJSONformat.

Now, if you navigate back to theGETendpointhttp://127.0.0.1:8000/, you will see the food ‘Maziwa mala,’and Its description added.

You now have a REST API that can display and add items to the application. How about experimenting with otherCRUDmethods? Working withUPDATEandDELETEmethods will increase the functionality of your REST API.

How to Create a REST API With Django

You can now create a REST API using Django. First, create an App with a model, Serialize the data, and create a view function. Next, include URL endpoints to visualize the data in JSON format.

Building REST APIs with Django REST framework is a convenient way to share data and give your users a great customer experience.

Go end-to-end with this tutorial covering every part of a simple API’s journey.

You don’t need to fork out for expensive hardware to run an AI on your PC.

Quality apps that don’t cost anything.

Windows is great, but adding this makes it unstoppable.

When your rival has to bail out your assistant.

One casual AI chat exposed how vulnerable I was.

Technology Explained

PC & Mobile