Home Backend Development Python Tutorial Building a RESTful API using Django

Building a RESTful API using Django

Jun 17, 2023 pm 09:29 PM
restful api django

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<pk>[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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Django vs. Flask: A comparative analysis of Python web frameworks Django vs. Flask: A comparative analysis of Python web frameworks Jan 19, 2024 am 08:36 AM

Django and Flask are both leaders in Python Web frameworks, and they both have their own advantages and applicable scenarios. This article will conduct a comparative analysis of these two frameworks and provide specific code examples. Development Introduction Django is a full-featured Web framework, its main purpose is to quickly develop complex Web applications. Django provides many built-in functions, such as ORM (Object Relational Mapping), forms, authentication, management backend, etc. These features allow Django to handle large

Django Framework Pros and Cons: Everything You Need to Know Django Framework Pros and Cons: Everything You Need to Know Jan 19, 2024 am 09:09 AM

Django is a complete development framework that covers all aspects of the web development life cycle. Currently, this framework is one of the most popular web frameworks worldwide. If you plan to use Django to build your own web applications, then you need to understand the advantages and disadvantages of the Django framework. Here's everything you need to know, including specific code examples. Django advantages: 1. Rapid development-Djang can quickly develop web applications. It provides a rich library and internal

How to upgrade Django version: steps and considerations How to upgrade Django version: steps and considerations Jan 19, 2024 am 10:16 AM

How to upgrade Django version: steps and considerations, specific code examples required Introduction: Django is a powerful Python Web framework that is continuously updated and upgraded to provide better performance and more features. However, for developers using older versions of Django, upgrading Django may face some challenges. This article will introduce the steps and precautions on how to upgrade the Django version, and provide specific code examples. 1. Back up project files before upgrading Djan

How to deal with Laravel API error problems How to deal with Laravel API error problems Mar 06, 2024 pm 05:18 PM

Title: How to deal with Laravel API error problems, specific code examples are needed. When developing Laravel, API errors are often encountered. These errors may come from various reasons such as program code logic errors, database query problems, or external API request failures. How to handle these error reports is a key issue. This article will use specific code examples to demonstrate how to effectively handle Laravel API error reports. 1. Error handling in Laravel

Oracle API Usage Guide: Exploring Data Interface Technology Oracle API Usage Guide: Exploring Data Interface Technology Mar 07, 2024 am 11:12 AM

Oracle is a world-renowned database management system provider, and its API (Application Programming Interface) is a powerful tool that helps developers easily interact and integrate with Oracle databases. In this article, we will delve into the Oracle API usage guide, show readers how to utilize data interface technology during the development process, and provide specific code examples. 1.Oracle

Oracle API integration strategy analysis: achieving seamless communication between systems Oracle API integration strategy analysis: achieving seamless communication between systems Mar 07, 2024 pm 10:09 PM

OracleAPI integration strategy analysis: To achieve seamless communication between systems, specific code examples are required. In today's digital era, internal enterprise systems need to communicate with each other and share data, and OracleAPI is one of the important tools to help achieve seamless communication between systems. This article will start with the basic concepts and principles of OracleAPI, explore API integration strategies, and finally give specific code examples to help readers better understand and apply OracleAPI. 1. Basic Oracle API

Is Django front-end or back-end? check it out! Is Django front-end or back-end? check it out! Jan 19, 2024 am 08:37 AM

Django is a web application framework written in Python that emphasizes rapid development and clean methods. Although Django is a web framework, to answer the question whether Django is a front-end or a back-end, you need to have a deep understanding of the concepts of front-end and back-end. The front end refers to the interface that users directly interact with, and the back end refers to server-side programs. They interact with data through the HTTP protocol. When the front-end and back-end are separated, the front-end and back-end programs can be developed independently to implement business logic and interactive effects respectively, and data exchange.

How to use the Django framework to create a project in PyCharm How to use the Django framework to create a project in PyCharm Feb 19, 2024 am 08:56 AM

Tips on how to create projects using the Django framework in PyCharm, requiring specific code examples. Django is a powerful Python Web framework that provides a series of tools and functions for quickly developing Web applications. PyCharm is an integrated development environment (IDE) developed in Python, which provides a series of convenient functions and tools to increase development efficiency. Combining Django and PyCharm makes it faster and more convenient to create projects

See all articles