Building a RESTful API using Django

PHPz
Release: 2023-06-17 21:29:38
Original
1085 people have browsed it

Django is a web framework that makes it easy to build RESTful APIs. RESTful API is a web-based architecture that can be accessed through HTTP protocol. In this article, we'll cover how to use Django to build a RESTful API, including how to use the Django REST framework to simplify the development process.

  1. Installing Django

First, we need to install Django locally. You can use pip to install Django. The specific command is as follows:

pip install Django
Copy after login
  1. Create Django project

After installing Django, we can create a Django project by running the following command:

django-admin startproject projectname
Copy after login

Among them, projectname is the name of the project you want to create.

  1. Create a Django application

A Django project consists of applications. We need to create an application in the project to build a RESTful API. You can create an application by running the following command:

python manage.py startapp appname
Copy after login

where appname is the name of the application you want to create.

  1. Configuring the database

By default, Django uses SQLite as its default database. If you want to change the database, you can configure it in the project's settings.py file.

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'mydatabase',
        'USER': 'mydatabaseuser',
        'PASSWORD': 'mypassword',
        'HOST': '127.0.0.1',
        'PORT': '5432',
    }
}
Copy after login
  1. Create a model

In Django, a model is a class used to maintain data. We need to create the model associated with the RESTful API.

from django.db import models

class Article(models.Model):
    title = models.CharField(max_length=200)
    content = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
Copy after login

In this example we create a model called Article which has title, content and created_at Field.

  1. Create a serializer

The serializer is used to serialize the model into JSON format for delivery to the client. This process can be simplified using the serializers provided by the Django REST framework.

from rest_framework import serializers
from .models import Article

class ArticleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Article
        fields = ('id', 'title', 'content', 'created_at')
Copy after login

In this example, we create a serializer named ArticleSerializer that serializes the Article model to contain id## JSON format for the #, title, content and created_at fields.

    Create View
View is used to process HTTP requests and return responses to the client. This process can be simplified using the view classes provided by the Django REST framework.

from rest_framework import generics
from .models import Article
from .serializers import ArticleSerializer

class ArticleList(generics.ListCreateAPIView):
    queryset = Article.objects.all()
    serializer_class = ArticleSerializer

class ArticleDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = Article.objects.all()
    serializer_class = ArticleSerializer
Copy after login

In this example, we create a view class

ArticleList and ArticleDetail. The ArticleList class handles GET and POST requests, the ArticleDetail class handles GET, PUT and DELETE requests. They both use the Article model and the ArticleSerializer serializer.

    Add URL
We need to map the view to a URL so that clients can access the RESTful API. This can be configured in the

urls.py file of the application.

from django.conf.urls import url
from .views import ArticleList, ArticleDetail

urlpatterns = [
    url(r'^articles/$', ArticleList.as_view(), name='article-list'),
    url(r'^articles/(?P[0-9]+)/$', ArticleDetail.as_view(), name='article-detail'),
]
Copy after login

In this example, we map the

ArticleList and ArticleDetail views to the URLs /articles/ and /articles/< ;pk>/. is the primary key of the Article model.

    Running Server
Now we can run the Django server and try to get data from the RESTful API.

python manage.py runserver
Copy after login
Visit

http://127.0.0.1:8000/articles/ to get a list of all instances of the Article model. Visit http://127.0.0.1:8000/articles// to get the details of a single Article model instance.

Summary:

This article introduces how to use Django to build a RESTful API. By following the above steps, you can easily build a RESTful API and use the Django REST framework to simplify the development process. RESTful APIs are an important part of creating web applications, so Django provides good support and tools to help developers build powerful RESTful APIs.

The above is the detailed content of Building a RESTful API using Django. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!