Home Backend Development Python Tutorial Use the Django framework to build RESTful APIs

Use the Django framework to build RESTful APIs

Sep 28, 2023 pm 09:01 PM
restful api django

Use the Django framework to build RESTful APIs

Use the Django framework to build RESTful APIs

With the continuous development of web applications, building scalable and flexible APIs has become important for modern applications component. As a popular development framework, the Django framework provides us with a fast and reliable way to build RESTful APIs. This article will introduce how to use the Django framework to build a RESTful API and provide specific code examples.

  1. Creating Django Projects and Applications
    First, we need to create a Django project in the local environment. Use the following command to create a project named "myproject".

1

$ django-admin startproject myproject

Copy after login

Go to the project directory and create an application named "api".

1

2

$ cd myproject

$ python manage.py startapp api

Copy after login
  1. Configuring projects and applications
    In the settings.py file of the project, we need to add the "rest_framework" and "api" applications to the INSTALLED_APPS list.

1

2

3

4

5

INSTALLED_APPS = [

    ...

    'rest_framework',

    'api',

]

Copy after login

You also need to configure the urls.py file of the project to forward the request path to our API application.

1

2

3

4

5

6

from django.urls import include, path

 

urlpatterns = [

    ...

    path('api/', include('api.urls')),

]

Copy after login
  1. Creating models and serializers
    In our application API, we need to first define the model class to represent the resources in our API. Taking an article as an example, we can define a model named "Article" in the models.py file.

1

2

3

4

5

6

from django.db import models

 

class Article(models.Model):

    title = models.CharField(max_length=100)

    content = models.TextField()

    created_at = models.DateTimeField(auto_now_add=True)

Copy after login

Next, we need to create a file named serializers.py in the api directory and define a serializer named "ArticleSerializer" to convert the model instance to JSON.

1

2

3

4

5

6

7

from rest_framework import serializers

from api.models import Article

 

class ArticleSerializer(serializers.ModelSerializer):

    class Meta:

        model = Article

        fields = ['id', 'title', 'content', 'created_at']

Copy after login
  1. Create Views
    Create a file named views.py in the api directory and add a class view named ArticleList to handle GET and POST requests.

1

2

3

4

5

6

7

from rest_framework import generics

from api.models import Article

from api.serializers import ArticleSerializer

 

class ArticleList(generics.ListCreateAPIView):

    queryset = Article.objects.all()

    serializer_class = ArticleSerializer

Copy after login

We can also create a class view called ArticleDetail to handle GET, PUT and DELETE requests for a single article.

1

2

3

4

5

6

7

from rest_framework import generics

from api.models import Article

from api.serializers import ArticleSerializer

 

class ArticleDetail(generics.RetrieveUpdateDestroyAPIView):

    queryset = Article.objects.all()

    serializer_class = ArticleSerializer

Copy after login
  1. Configure URL
    Create a file named urls.py in the api directory and add the following code to configure the path.

1

2

3

4

5

6

7

from django.urls import path

from api import views

 

urlpatterns = [

    path('articles/', views.ArticleList.as_view(), name='article-list'),

    path('articles/<int:pk>/', views.ArticleDetail.as_view(), name='article-detail'),

]

Copy after login
  1. Start the service
    Now we can run the development server and test our API.

1

$ python manage.py runserver

Copy after login
  1. Testing API
    Using tools such as Postman or curl, etc., you can send HTTP requests to test the API. Here are some common API request examples.
  • Get all articles (GET request):

    1

    GET http://localhost:8000/api/articles/

    Copy after login
  • Get a single article (GET request):

    1

    GET http://localhost:8000/api/articles/1/

    Copy after login
  • Create new article (POST request):

    1

    2

    3

    4

    5

    6

    7

    POST http://localhost:8000/api/articles/

    Content-Type: application/json

     

    {

      "title": "Hello",

      "content": "This is a test article."

    }

    Copy after login
  • Update article (PUT request):

    1

    2

    3

    4

    5

    6

    7

    PUT http://localhost:8000/api/articles/1/

    Content-Type: application/json

     

    {

      "title": "Hello World",

      "content": "This is an updated test article."

    }

    Copy after login
  • Delete article (DELETE request):

    1

    DELETE http://localhost:8000/api/articles/1/

    Copy after login

    Summary:
    In this article, we introduced how to use the Django framework to build a RESTful API. By creating models and serializers, defining views and URL configurations, we can quickly build a fully functional API and test it. This provides a good foundation for us to build modern web applications and provide scalable services. Using the Django framework, we can easily handle common API needs such as getting, creating, updating, and deleting resources.

    (Word count: 1063)

    The above is the detailed content of Use the Django framework to build RESTful APIs. 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

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.

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

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