This content originally appeared on Level Up Coding - Medium and was authored by Okan Yenigün
RESTful Django — Django REST Framework
Let’s Develop a RESTful Django Project
Django does not directly support Restful API. But thanks to the REST Framework package, we can create Restful APIs in Django projects. You can check out the official documentation here. In this blog post, I will explain how to create REST APIs in Django projects.
Content
- What is an API?
- What is REST API?
- Django REST Framework
API
The word API stands for Application Programming Interface. They are responsible for making the two software units talk to each other.
Consider a web app or mobile app. When you visit a web application, a react application is downloaded by your browser. so you can view their website. When the data request occurs, the user is not allowed to access the databases directly from an architectural point of view. That would be very dangerous. Instead, we are trying to control how people and what people can do with the data in our database.
By designing a REST API, we construct another structure that is discrete between the two structures. In this way, we set out and manage how to connect to the database.
In today’s applications, we have multiple data sources and we need to utilize them to develop better applications.
REST Architecture
REST is an acronym for Representational State Transfer. It is a universal architecture with defined standards for how APIs should work. APIs created in accordance with REST standards are called REST APIs, and web services that use them are called RESTful web services. A REST API has to fulfill some principles.
Stateless
Every request from the client must carry all the necessary information and this information cannot be stored on the server side. There is no state information on the server. The client provides the necessary information.
In stateful architecture, information is stored with global variables on the server side. For example, in a web application, the client logs in first. This information is also kept in a variable such as is_logged on the server side. In subsequent operations (such as page views, etc.), this variable is checked and acts accordingly. However, in this structure, as seen in the figure above, there is a problem if there is more than one server. If the user logged in to server 1 is redirected to another server by the load balancer, he must log in again.
In stateless architecture, no state information is kept on the server side. A token is shared with the client. When the client makes a request, it also sends the token information. In this way, it works in harmony with more than one server.
Statelessness makes the REST API easily scalable. Since we don’t need to save any state information, each server must be able to keep track of the client’s requests.
Since there is no need for state synchronization, we reduce the complexity of the system.
Each request of the client occurs in isolation. Thus, the server does not need to keep track of client requests. This also increases performance.
Requests will be slightly larger as they contain information such as tokens.
Client-Server
Client and server are two different components in a system. In accordance with the principle of separation of concerns, these two components should work separately from each other. In this way, the user interface and data storage operations work independently of each other.
By using the client-server design pattern, we increase the portability of the user interface. We will make it easily available on multiple platforms. Besides, the scalability of the server component is improved because it works independently from the user interface.
Uniform Interface
Every service must use the HTTP interface the same way. The server must transfer its information in a standard format. For example, we use GET request to get or read information and this is globally the same. It helps to maintain uniformity across applications on the web. By doing that, the architecture is decoupled for scaling.
There are 4 architectural constraints to achieve this uniformity:
Identification of resources: REST is resource-oriented. In the REST structure, a resource is a piece of abstracted information. Any information is a resource. The state of a resource at any given moment is called the resource representation. It contains data, metadata describing the data, and hypermedia links.
Each resource should be identified by a unique identifier which is the Unique Resource Identifier. A hierarchical approach is used when creating a URI. For example
www.example.com/users/{{userId}}/comments/{{commentId}}
The identifier doesn’t have any relation with the format of the responses.
Identifiers shouldn’t change. It should always follow some hierarchical approach
Resource manipulations: The client should have the ability to manipulate the resource. Therefore, it should have enough information about the resource representation. The server provides the representation of resources. It can be any format such as JSON, XML, HTML, images, etc.
Accept : application/json, which will define the format of the response, without any change in URI.
www.example.com/users/1/comments/23
Accept: application/json
OR
www.example.com/users/1/comments/23
Accept: application/xml
So, the client will request a response in a certain format based on needs, this is known as “Content Negotiation”.
Self-Descriptive messages: In stateless communication, the server doesn’t keep track of the state and client, and every request is independent of each other. So, all the necessary information about the request itself should be included in the request. That is, the request is self-explanatory.
This can be done via method types. We can use different methods like GET (read), PUT (modify), or DELETE for the same url.
We can also put this information in the metadata. And metadata can be placed into the body or header.
Hypermedia as the engine of the application state (HATEOAS): Accessing an API should be similar to accessing a web page. The client should be able to access other parts of the API from the response. The response of an API should include links to other related resources.
www.example.com/users/1/comments/23
{
"userId":"xxx",
"msg":"asd",
"links":[{
"rel":"delete",
"link":"/comment/23"},
{"rel":"edit",
"link":"/comment/23"}
]
}
Cacheable
The server marks every response as cacheable or non-cacheable. The client can cache the response and will return it from its cache next time. Thus, it won’t have to send the same request again. Hereby, interactions between the client and the server would be reduced. It supports scalability and performance.
Layered System
There can be n number of layers in an architecture. Each layer should have a unique responsibility and each one of them shouldn’t know anything about any other layer but can interact with others.
Code on Demand (Optional)
A client can download features or the source code. For example, when you fill out a form, the browser will indicate the errors in the form. For example, an email address in the wrong format. The browser can do this with the code sent by the server.
Methods
- GET: Retrieve information about the source
- POST: Create a REST resource
- PUT: Update a resource
- DELETE: Delete a resource
REST Framework
For demonstration purposes, I have created a template Django project. The GitHub link is here.
In this project, we have only one app called api.
Installation
So, the first thing to do is to install the Django REST Framework package:
pip install djangorestframework
Later, add it to the app list in settings.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'api',
'rest_framework',
]
Models
I have created a simple Model named Movie:
Urls
Next, let’s create endpoints in the urls.py in the api app. Later we will see that we can build Views in two ways, by using methods or by using view classes. If we use the methods for views:
urlpatterns = [
path('', movie_create),
path('list/', get_movies),
path('<int:pk>', movie)
]
Or for view classes:
urlpatterns = [
path('',MovieCreate.as_view()),
path('list/', MovieList.as_view()),
path('<int:pk>',MovieRecord.as_view())
]
Serializers
Now, we can create serializers in a new file called serializers.py. Serializers convert querysets into JSON contents.
We need to map serializers to models. We can do this in two ways. In the first method, we manually match the model fields with the fields of the serializer. We need to define separate methods for new record creation and update operations and again we need to pass information to the model.
Or, we can define a metaclass and the above process can be automated.
We can also customize validation processes. validate_xfield method checks the given field. Or, we can define a general method for validation.
We can define fields for serializers. get_x type of methods automatically appends fields, i.e. description -> get_description()
Views
Firstly, let’s examine method views.
GET: We retrieve data from models and send them into the serializer. Later we return a response.
POST: We send the data located inside the request to the serializer. Before saving it, we should check if the data is valid.
PUT & DELETE: The record to be updated (or deleted) is retrieved using the primary key. If there isn’t any record, we send an error. Necessary operations are performed according to the method type sent in the request.
The second way (and the better way) is using view classes. APIView class is inherited.
Endpoints
Finally, let’s take a look at endpoint URLs and try some functionalities.
To create a new record:
http://127.0.0.1:8000/movies/
We inserted a new record. You can notice that it created a new “description” field by itself.
Let’s list all records:
http://127.0.0.1:8000/movies/list/
We can update any record:
http://127.0.0.1:8000/movies/2
That’s all for now about Django REST Framework. Thank you for reading this far. You can follow me and subscribe to be aware of similar content and to read my other blog posts. Thank you.
Read More
- Learn Django Signals
- Autocomplete Search Suggestions in Django
- Scala #5: Classes
- Design Patterns in Python: Command Pattern
References
https://www.django-rest-framework.org/#example
https://www.youtube.com/watch?v=mlr9BF4JomE
https://aws.amazon.com/tr/what-is/restful-api/
https://www.hosting.com.tr/bilgi-bankasi/rest-api/
RESTful Django — Django REST Framework was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.
This content originally appeared on Level Up Coding - Medium and was authored by Okan Yenigün
Okan Yenigün | Sciencx (2022-09-21T02:01:01+00:00) RESTful Django — Django REST Framework. Retrieved from https://www.scien.cx/2022/09/21/restful-django-django-rest-framework/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.