If youve used a digital machine to send and receive information, youve 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 free to build one from scratch.
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.
Its customizable features make it a popular choice to build REST APIs.
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.
Register the App Project controls
Register thekenyanfoodapp in the project controls under theINSTALLED APPSarray.
If you skip this step, Django will not recognize the app.
Also, register the Django REST framework in the same configs:
4.
Register App URLs
Registerkenyanfoodapp URLs in the projecturls.pyfile as illustrated below:
5.
First, import theResponseobjectand@apiviewdecorator from the Django REST framework.
Responsehelps return sterilized data inJSONformat while the@apiviewdisplays the API.
Create a URL Path for the App
Create a URL path for the API view you created.
This endpoint displays thekenyanfooddata.
Make Migrations
Next,migratethe app to create tables in theSQLitedatabase.
In this guide, you will use the Django admin interface.
These are both for authentication; theFoodmodel is in the section below.
you might 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.
Next, specify theFoodmodel you want to serialize and the fields you want to add to the API.
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.
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.
You now have a REST API that can display and add items to the tool.
How about experimenting with otherCRUDmethods?
Working withUPDATEandDELETEmethods will increase the functionality of your REST API.
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.