Keywords: Python, Web development, Django, RESTful API
1 Some things about API
1.1 What are APIs?
API is the abbreviation of Application Programming Interface (Application Programming Interface). It is a specification that defines how different software components interact with each other. API allows communication and data exchange between different applications, enabling developers to utilize functions and data provided by other applications without knowing their internal implementation details.
In web development, APIs are often a means for building and accessing web services. Through the API, developers can send and receive data through HTTP requests, thereby realizing data transmission and interaction between different applications.
1.2 API Types for Web Development
In web development, there are several common API types:
1.2.1. Web Service APIs:
This API uses standard Web technologies such as HTTP and XML to communicate. Two of the common types of web service APIs are SOAP and REST.
-
SOAP (Simple Object Access Protocol):
It uses XML format for data exchange and transfers via HTTP or other protocols. SOAP provides an XML-based communication mechanism to describe APIs by defining message structures and service operations. SOAP API usually uses WSDL (Web Services Description Language) to define the structure and operation of the API. -
REST (Representational State Transfer):
It is a lightweight web-based architectural style. REST API uses different methods of HTTP protocol such as GET, POST, PUT, DELETE to perform operations on data. It usually uses JSON or XML format for data exchange. REST API is by far the most commonly used type of web service API.
1.2.2. Third-Party APIs:
These APIs are provided by third parties to allow developers to access their services or data. For example, social media platforms such as Twitter and Facebook provide APIs that enable developers to use functions and data on their platforms. Third-party APIs are often RESTful and require developers to authenticate to gain access.
1.2.3. Custom API:
In web development, you can also build your own custom APIs to serve your applications. These APIs can be designed and implemented according to the needs of the application and communicate using standard web technologies.
2 Introduction to RESTful APIs
Before we learn more about how Django designs RESTful API, let's first understand the basic concepts and principles of RESTful API.
2.1 What are RESTful APIs?
RESTful API (Representational State Transfer) is a design style for building network services in distributed systems. It is based on a set of concise principles and constraints, enabling different systems to communicate and interact through the HTTP protocol.
2.2 Principles of RESTful API
The design principles of RESTful API are as follows:
-
Resources : abstract the entities (resources) in the system into a unified resource model, and uniquely identify them through URI (Uniform Resource Identifier).
-
Verbs : Use HTTP methods (GET, POST, PUT, DELETE, etc.) to express different operations on resources.
-
State transfer : Operations on resources are realized through requested state transfers (such as creation, update, deletion, etc.).
-
Stateless : Each request is independent, and the server does not save the client's state information.
3 Django's RESTful API design practice
Well, now that we have a preliminary understanding of Django and RESTful API, let's delve into the RESTful API design practice under the Django framework. I will take you step by step to implement a sample project with practical functions, so that you can better understand and master Django's API design skills.
3.1 Project introduction
This project is a simple to-do list management application. Users can create, view, update and delete to-dos. This project will help us understand how to design Django applications that adhere to RESTful API principles.
3.2 Create a Django project
First create a Django project. Open your terminal or command prompt and create a new Django project with the following command:
django-admin startproject todoapp
Running it will create a todoapp
new directory named , and generate the initial structure of the Django project in it.
3.3 Creating an application
Next create a Django application. Change into the directory in a terminal todoapp
and run the following command:
python manage.py startapp todos
3.4 Define the data model
Before we start designing the API view, we need to define the data model for the backlog. Open todos/models.py
the file and add the following code in it:
from django.db import models
class Todo(models.Model):
title = models.CharField(max_length=200)
description = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
completed = models.BooleanField(default=False)
def __str__(self):
return self.title
Here we define a Todo
data model called , which contains title
, description
, created_at
and completed
fields. __str__
method is used to return a string representation of the model object.
3.5 Create an API view
Now, we can start creating API views. In todos/views.py
the file, add the following code:
from rest_framework import viewsets
from .models import Todo
from .serializers import TodoSerializer
class TodoViewSet(viewsets.ModelViewSet):
queryset = Todo.objects.all()
serializer_class = TodoSerializer
Here we use the classes provided by Django REST Framework viewsets.ModelViewSet
to define a view set. We specify the queryset and serializer classes, and Django REST Framework will automatically generate common CRUD (create, read, update, delete) operations.
3.6 Configure URL Routing
In order for Django to know how to map URLs to our API views, we need to configure URL routing. Open todoapp/urls.py
the file and add the following code:
from django.urls import include, path
from rest_framework import routers
from todos.views import TodoViewSet
router = routers.DefaultRouter()
router.register(r'todos', TodoViewSet)
urlpatterns = [
path('', include(router.urls)),
]
Here we use the classes provided by Django REST Framework DefaultRouter
to automatically generate URL routes and TodoViewSet
register views /todos
under the routes.
Equivalent to manually configuring the following routes:
GET /todos/: Get a list of all todos
POST /todos/: Create a new todo
GET /todos/{pk}/: Get details for a specific todo
PUT /todos/{pk}/: Update Details of a specific todo
PATCH /todos/{pk}/: Partially update the details of a specific todo
DELETE /todos/{pk}/: Delete a specific todo
3.7 Running the development server
The configuration of the API view and URL routing is now complete. It's time to start the Django development server and test the API. Run the following command in a terminal:
python manage.py runserver
After the server starts, you can visit it in your browser http://localhost:8000/todos
to view the root path of the API. You can also use tools such as Postman to test the API.
3.8 Summary of sample code
Through the above steps, we have successfully created a simple to-do management API. We defined the data model, created the API view, and mapped it to the appropriate path through URL routing. In the future, you can expand and customize this API according to your own needs.
3.9 Adding a serializer
The project uses a serializer to convert model data into JSON format. Now create a serializer to define how to serialize and deserialize the todo model.
In todos/serializers.py
the file, add the following code:
from rest_framework import serializers
from .models import Todo
class TodoSerializer(serializers.ModelSerializer):
class Meta:
model = Todo
fields = '__all__'
Here we imported serializers
the module and created a TodoSerializer
serializer class called , specifying the model class and the collection of fields to serialize. All fields can be '__all__'
serialized using the representation.
3.10 Running database migrations
Before using the new data model and serializer, you need to run database migrations to create the corresponding data tables. Run the following command in a terminal:
python manage.py makemigrations
python manage.py migrate
3.11 Testing APIs
We have now completed the design and configuration of the API. Let's test that our API is working.
The API can be tested by sending HTTP requests using a browser or an API testing tool. Here are some sample requests:
-
Get all todos : Send a GET request to
http://localhost:8000/todos/
. -
Create a new todo : Send a POST request to
http://localhost:8000/todos/
and include the todo's data in the request body. -
Get a single todo : Send a GET request to
http://localhost:8000/todos/{id}/
, where{id}
is the ID of the todo. -
Update to-do items : Send a PUT or PATCH request to
http://localhost:8000/todos/{id}/
and include updated to-do item data in the request body. -
Delete to-do item : send DELETE request to
http://localhost:8000/todos/{id}/
, where{id}
is the ID of the to-do item.
Request testing can be done according to your needs and the requirements of the tool.
3.12 Authentication and permission control
In practical applications, it is usually necessary to implement authentication and permission control on the API to ensure that only authorized users can access and modify data.
Django REST Framework provides various authentication and permission control options. For example, you can use token authentication, JWT (JSON Web Token) authentication, or OAuth-based authentication to protect your API.
You can also use decorators (a concept similar to annotations), permission classes, and attributes of view sets to define various access control rules, such as only allowing users with specific permissions to perform operations.
关于这个详细的内容比较多,我们后续另起一篇文章分享。
3.13 Other functions and extensions
Django REST Framework provides many other features and extensions to help you better build and manage RESTful APIs.
Some common features and extensions include:
-
Pagination : When dealing with large amounts of data, you can use pagination to limit the size of the result set and provide links to the next and previous pages.
-
Filtering and Searching : Allows users to filter and search data based on specified criteria.
-
Sorting : Allows users to sort data by specified fields.
-
Version Control : Allows you to manage and control different versions of API interfaces.
-
Cache : Provide caching function to improve API performance and response speed.
That's all for today's sharing. If the content of the article is helpful to you, please like, collect and forward, thank you.