django-rest-framework README

The project's README from github.com/encode/django-rest-framework. As one markdown file: README.md.

Django REST framework

build-status-image coverage-status-image pypi-version

Awesome web-browsable Web APIs.

Full documentation for the project is available at https://www.django-rest-framework.org/.


Overview

Django REST framework is a powerful and flexible toolkit for building Web APIs.

Some reasons you might want to use REST framework:

Below: Screenshot from the browsable API

Screenshot


Requirements

We highly recommend and only officially support the latest patch release of each Python and Django series.

Installation

Install using pip...

pip install djangorestframework

Add 'rest_framework' to your INSTALLED_APPS setting.

INSTALLED_APPS = [
    # ...
    "rest_framework",
]

Example

Let's take a look at a quick example of using REST framework to build a simple model-backed API for accessing users and groups.

Start up a new project like so...

pip install django
pip install djangorestframework
django-admin startproject example .
./manage.py migrate
./manage.py createsuperuser

Now edit the example/urls.py module in your project:

from django.contrib.auth.models import User
from django.urls import include, path
from rest_framework import routers, serializers, viewsets


# Serializers define the API representation.
class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = ["url", "username", "email", "is_staff"]


# ViewSets define the view behavior.
class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer


# Routers provide a way of automatically determining the URL conf.
router = routers.DefaultRouter()
router.register(r"users", UserViewSet)

# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
    path("", include(router.urls)),
    path("api-auth/", include("rest_framework.urls", namespace="rest_framework")),
]

We'd also like to configure a couple of settings for our API.

Add the following to your settings.py module:

INSTALLED_APPS = [
    # ... make sure to include the default installed apps here.
    "rest_framework",
]

REST_FRAMEWORK = {
    # Use Django's standard `django.contrib.auth` permissions,
    # or allow read-only access for unauthenticated users.
    "DEFAULT_PERMISSION_CLASSES": [
        "rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly",
    ]
}

That's it, we're done!

./manage.py runserver

You can now open the API in your browser at http://127.0.0.1:8000/, and view your new 'users' API. If you use the Login control in the top right corner you'll also be able to add, create and delete users from the system.

You can also interact with the API using command line tools such as curl. For example, to list the users endpoint:

$ curl -H 'Accept: application/json; indent=4' -u admin:password http://127.0.0.1:8000/users/
[
    {
        "url": "http://127.0.0.1:8000/users/1/",
        "username": "admin",
        "email": "[email protected]",
        "is_staff": true,
    }
]

Or to create a new user:

$ curl -X POST -d username=new -d [email protected] -d is_staff=false -H 'Accept: application/json; indent=4' -u admin:password http://127.0.0.1:8000/users/
{
    "url": "http://127.0.0.1:8000/users/2/",
    "username": "new",
    "email": "[email protected]",
    "is_staff": false,
}

Documentation & Support

Full documentation for the project is available at https://www.django-rest-framework.org/.

For questions and support, use the REST framework discussion group, or #restframework on libera.chat IRC.

Security

Please see the security policy.

django-rest-framework (encode/django-rest-framework)

Searching Database…

Что это такое?Django REST framework — это мощный и гибкий набор инструментов для создания веб-API на Django: вы подключаете его к проекту и получаете полноценный REST API вокруг своих данных.
Это отдельное приложение или то, что добавляется в мой Django-проект?Это не отдельное приложение: вы устанавливаете пакет через pip install djangorestframework и добавляете 'rest_framework' в INSTALLED_APPS, после чего он живёт внутри вашего Django-проекта и превращает его в API.
Как запустить свой первый API?Установите django и djangorestframework через pip, выполните django-admin startproject, добавьте 'rest_framework' в settings и настройте urls.py, затем запустите ./manage.py runserver; пример из README заканчивается работающим API пользователей прямо в браузере.
Какие версии Python и Django поддерживаются?Python 3.10+ и Django 5.2, 6.0 или 6.1; официально поддерживается только последний патч-релиз каждой серии версий, поэтому лучше не отставать от обновлений.
Я ограничен generic views и viewsets или могу писать обычные вьюхи?Ни то, ни другое: фреймворк настраивается на любую глубину, так что обычные function-based views вполне подойдут, если вам не нужны более мощные generic views, viewsets и роутеры.
Сериализаторы работают только с моделями Django?Нет — сериализация поддерживает и данные из ORM, и источники без ORM, так что обычные объекты Python и другие источники тоже подходят.
Можно работать с API из командной строки, а не через браузер?Да, это обычный HTTP: в README показано, как через curl с базовой аутентификацией (-u admin:password) и заголовком 'Accept: application/json; indent=4' получать список пользователей и создавать новых, получая красиво отформатированный JSON.
API понимает только JSON?В примерах из README возвращается JSON, но те же эндпоинты, открытые в браузере, показывают удобный HTML-интерфейс; формат ответа зависит от заголовка Accept, который вы отправляете.
What are similar projects?martini, node-restify, echo, hapi, starlette, django-allauth, ky, grape
Creator
encode
Size
64.7 MB
Stars
30.2K
Age
15y
Commits · 90 Days