Django REST APIs Demystified: Simplifying API Development with Django / Понятный Django REST APIs: Упрощение разработки API с помощью Django
Год издания: 2025
Автор: Patil Ganeshkumar / Патил Ганешкумар
Издательство: Apress Media LLC
ISBN: 979-8-8688-1850-9
Язык: Английский
Формат: PDF/EPUB
Качество: Издательский макет или текст (eBook)
Интерактивное оглавление: Да
Количество страниц: 479
Описание: This book is designed to help you master API development using the Django REST Framework (DRF). Written for seasoned developers, this book offers practical, hands-on guidance to becoming an expert in using DRF, providing in-depth coverage of the framework's features and best practices and their application in API development.
The book will introduce you to and enable you to grasp advanced DRF topics such as authentication, permissions, throttling, caching, API versioning, and schema generation. Each chapter of the book focuses on a specific topic and introduces a standalone Django application that will ensure a structured and isolated learning experience for you. Real-world examples and step-by-step instructions provide a practical approach to building DRF APIs. The book also aids you in exploring customizing DRF for complex use cases, integrating third-party tools, and writing unit tests for secure, robust APIs. Special attention is given to working with multi-application Django projects, offering conventions to avoid conflicts and ensure clear API documentation.
By the end of this book, you will have the skills to build secure, scalable, and maintainable APIs using DRF. Whether you're working on a startup, enterprise project, or personal venture, this book equips you with the knowledge and tools to create efficient, future-proof APIs.
What You Will Learn
How to manage and structure complex multi-application projects without conflicts, leveraging best practices
Optimizing API Performance and Implementing advanced techniques like throttling, caching, and efficient query handling to enhance API performance.
Use versioning, customization, and extensible patterns to create APIs that adapt to evolving business requirements.
Who Is This Book For:
Web developers, front-end engineers, full stack engineers, API documentation specialists, technical leads.
Эта книга предназначена для того, чтобы помочь вам освоить разработку API с использованием платформы Django REST Framework (DRF). Эта книга, написанная для опытных разработчиков, предлагает практические рекомендации, как стать экспертом в использовании DRF, подробно описывая функции фреймворка и лучшие практики, а также их применение при разработке API.
Книга познакомит вас с такими продвинутыми темами DRF, как аутентификация, разрешения, регулирование, кэширование, управление версиями API и генерация схем, и позволит вам вникнуть в них. Каждая глава книги посвящена определенной теме и представляет отдельное приложение Django, которое обеспечит вам структурированный и изолированный процесс обучения. Реальные примеры и пошаговые инструкции дают практический подход к созданию DRF API. Книга также поможет вам изучить настройку DRF для сложных случаев использования, интеграцию сторонних инструментов и написание модульных тестов для безопасных и надежных API. Особое внимание уделяется работе с многопользовательскими проектами на Django, предлагаются соглашения, позволяющие избежать конфликтов и обеспечить понятную документацию по API.
К концу этой книги вы овладеете навыками создания безопасных, масштабируемых и поддерживаемых API с использованием DRF. Независимо от того, работаете ли вы над стартапом, корпоративным проектом или личным предприятием, эта книга снабдит вас знаниями и инструментами для создания эффективных, перспективных API.
Чему вы научитесь
Как управлять сложными проектами с несколькими приложениями и структурировать их без конфликтов, используя лучшие практики
Оптимизация производительности API и внедрение передовых методов, таких как регулирование, кэширование и эффективная обработка запросов, для повышения производительности API.
Используйте управление версиями, настройку и расширяемые шаблоны для создания API, которые адаптируются к меняющимся бизнес-требованиям.
Для кого предназначена эта книга:
Веб-разработчики, front-end инженеры, инженеры полного цикла, специалисты по документации API, технические руководители.
Примеры страниц (скриншоты)
Оглавление
About the Author ...................................................................................................xiii
About the Technical Reviewer .................................................................................xv
Acknowledgments .................................................................................................xvii
Introduction ............................................................................................................xix
Chapter 1:
Introduction to APIs ................................................................................1Private API .....................................................................................................................................2Public API ......................................................................................................................................2Partner API ....................................................................................................................................2RESTful APIs (Representational State Transfer) ............................................................................3SOAP APIs (Simple Object Access Protocol) ..................................................................................3GraphQL APIs .................................................................................................................................3JSON-RPC and XML-RPC APIs .......................................................................................................4WebSocket APIs ............................................................................................................................4gRPC APIs ......................................................................................................................................4Chapter 2:
REST API Concepts ..................................................................................5Web APIs .......................................................................................................................................5Endpoint ........................................................................................................................................5HTTP Methods ...............................................................................................................................6GET Method ...................................................................................................................................6POST Method ...........................................................................................................................6PUT Method .............................................................................................................................7PATCH Method .........................................................................................................................7DELETE Method .......................................................................................................................7Other Methods .........................................................................................................................8
Table of Contents
vi
HTTP Request ................................................................................................................................8HTTP Response .............................................................................................................................9Request Parameters ...................................................................................................................10Chapter 3:
Project Configuration ............................................................................13Environment ................................................................................................................................13Project Overview .........................................................................................................................14Project Setup ..............................................................................................................................14Chapter 4:
Django REST Framework .......................................................................19Serialization and Deserialization .................................................................................................19Viewsets and Serializers .............................................................................................................19Authentication and Permissions .................................................................................................20URL Routing and View Dispatching .............................................................................................20Request/Response Handling .......................................................................................................20Pagination and Filtering ..............................................................................................................20Content Negotiation ....................................................................................................................20Testing and Documentation ........................................................................................................21Why Django REST Framework ....................................................................................................21Chapter 5:
Postman ................................................................................................23Why Use Postman? .....................................................................................................................23Chapter 6:
Serializers and Views ...........................................................................25Using Serializer Fields ................................................................................................................25Preparing for This Chapter ..........................................................................................................26Create a Serializer .......................................................................................................................27Views ..........................................................................................................................................28Class-Based Views ................................................................................................................28Function-Based Views ...........................................................................................................29Implement Class-Based View for the Project ........................................................................29
Table of Contents
vii
Serializer Advanced Concepts .....................................................................................................31Nested Serializer ...................................................................................................................31Relational Fields ....................................................................................................................32Create a New Object ..............................................................................................................41Serializer Validation ...............................................................................................................43Get a Single Object ................................................................................................................45Update an Object ...................................................................................................................47Delete an Object ....................................................................................................................50Status Code ...........................................................................................................................51ModelSerializer ......................................................................................................................76HyperlinkedModelSerializer ...................................................................................................94ListSerializer ........................................................................................................................100BaseSerializer .....................................................................................................................105Advanced Serializer Usage ..................................................................................................112Generic Views ...........................................................................................................................116GenericAPIView ...................................................................................................................117Mixins ..................................................................................................................................128Concrete View Classes ........................................................................................................136Customizing the Generic Views ...........................................................................................149Chapter 7:
ViewsSets and Routers .......................................................................157Preparing for This Chapter ........................................................................................................159ViewSet .....................................................................................................................................161GenericViewSet .........................................................................................................................165ModelViewSet ...........................................................................................................................167ReadOnlyModelViewSet ............................................................................................................169Routers ......................................................................................................................................171Routing for Extra Actions ..........................................................................................................177Routing Additional HTTP Methods for Extra Actions ..................................................................180Custom Routers ........................................................................................................................182
Table of Contents
viii
Chapter 8:
Validators ............................................................................................187Validation in REST Framework ..................................................................................................189UniqueValidator .........................................................................................................................192UniqueTogetherValidator ...........................................................................................................193Unique Date/Month/Year Validator ............................................................................................194Writing Custom Validators .........................................................................................................195Preparing for This Chapter ........................................................................................................195Chapter 9:
Authentication .....................................................................................203How Authentication Is Determined ............................................................................................204Setting the Authentication Scheme ...........................................................................................206Unauthorized and Forbidden Responses ..................................................................................207Preparing for This Chapter ........................................................................................................209API Reference ...........................................................................................................................212BasicAuthentication .............................................................................................................213TokenAuthentication ............................................................................................................216SessionAuthentication .........................................................................................................231RemoteUserAuthentication ..................................................................................................232Custom Authentication ........................................................................................................234Chapter 10:
Permissions ......................................................................................239Default User Permissions ..........................................................................................................243Permissions Without App Label (Global Permissions) .........................................................244Permissions with App Label (Model-Specific Permissions) ................................................244How Permissions Are Determined ............................................................................................245View-Level Permission Checks ...........................................................................................245Object-Level Permission Checks (Optional) .........................................................................246Permission Evaluation Key Points .............................................................................................247Preparing for This Chapter ........................................................................................................248Setting the Permission Policy ...................................................................................................250Built-In Classes .........................................................................................................................252AllowAny ..............................................................................................................................253
Table of Contents
ix
IsAuthenticated ...................................................................................................................254IsAuthenticatedOrReadOnly .................................................................................................254IsAdminUser ........................................................................................................................255DjangoModelPermissions ....................................................................................................256DjangoModelPermissionsOrAnonReadOnly .........................................................................261DjangoObjectPermissions ....................................................................................................261Custom Permissions .................................................................................................................268Access Restriction Methods ......................................................................................................272Chapter 11:
Caching .............................................................................................275Preparing for This Chapter ........................................................................................................275View-Level Caching ..................................................................................................................277How View-Level Caching Works ..........................................................................................277Applying the @cache_page Decorator ................................................................................278Low-Level Caching (Custom Caching in Views or Functions) ...................................................280Limitations and Considerations ...........................................................................................282Cache Invalidation .....................................................................................................................283DRF Cache Mixins .....................................................................................................................283vary_on_headers ......................................................................................................................285Additional Notes ..................................................................................................................286vary_on_cookie ........................................................................................................................287Additional Notes ..................................................................................................................288Chapter 12:
Throttling ..........................................................................................289Why Use Throttling? ..................................................................................................................290Types of Throttling in DRF .........................................................................................................291AnonRateThrottle ......................................................................................................................291Key Features of AnonRateThrottle .......................................................................................291Example Scenario ................................................................................................................293UserRateThrottle .......................................................................................................................293Key Features of UserRateThrottle ........................................................................................293Example Scenario ................................................................................................................295
Table of Contents
x
ScopedRateThrottle ..................................................................................................................296How ScopedRateThrottle Works ..........................................................................................296Example Explanation ...........................................................................................................296Use Cases ............................................................................................................................297Practical Benefits ................................................................................................................298Preparing for This Chapter ........................................................................................................298How Throttling Is Determined ...................................................................................................300How Clients Are Identified .........................................................................................................300Setting Up the Cache ................................................................................................................301Cache Back End in DRF .......................................................................................................302Example of Custom Throttle Class with Custom Cache .......................................................302Configuring the Cache in settings.py ...................................................................................303Setting Up Throttling in DRF ......................................................................................................304Custom Throttling ......................................................................................................................307Explanation of the Methods .................................................................................................307A Note on Concurrency .............................................................................................................311Guaranteeing the Number of Requests ...............................................................................311Example of a More Robust Custom Throttle ........................................................................311Chapter 13:
Filtering
Searching, and Ordering ....................................................313Preparing for This Chapter ........................................................................................................313Filtering Against the Current User .............................................................................................315Filtering Against the URL ...........................................................................................................317Filtering Against Query Parameters ..........................................................................................319Generic Filtering ........................................................................................................................321Overriding the Initial queryset ...................................................................................................323API Guide ...................................................................................................................................325DjangoFilterBackend ...........................................................................................................325SearchFilter .........................................................................................................................326OrderingFilter ......................................................................................................................333Custom Generic Filtering ..........................................................................................................338Customizing the Interface .........................................................................................................340
Table of Contents
xi
Chapter 14:
Pagination .........................................................................................343Why Use Pagination? ................................................................................................................343How Pagination Works in DRF ...................................................................................................345Preparing for This Chapter ........................................................................................................345Default Pagination Classes in DRF ............................................................................................347PageNumberPagination .......................................................................................................347Configure Global Pagination Settings ..................................................................................348LimitOffsetPagination ..........................................................................................................352CursorPagination .................................................................................................................356Custom Pagination Styles .........................................................................................................362Chapter 15:
Versioning .........................................................................................371Versioning with REST Framework .............................................................................................371Configuring the Versioning Scheme ..........................................................................................373Global Configuration ............................................................................................................373Per-View Configuration ........................................................................................................374Customizing the Versioning Class .......................................................................................374Preparing for This Chapter ........................................................................................................375Types of API Versioning .............................................................................................................377URLPathVersioning ..............................................................................................................377NamespaceVersioning .........................................................................................................380NamespaceVersioning vs. URLPathVersioning ....................................................................384QueryParameterVersioning ..................................................................................................385AcceptHeaderVersioning .....................................................................................................388HostNameVersioning ...........................................................................................................391Custom Versioning Schemes ...............................................................................................392Chapter 16:
Testing ...............................................................................................397Preparing for This Chapter ........................................................................................................398APIRequestFactory ....................................................................................................................399Format Argument .................................................................................................................400PUT and PATCH with Form Data ..........................................................................................401
Table of Contents
xii
Forcing Authentication ........................................................................................................401CSRF Validation ...................................................................................................................402APIClient ....................................................................................................................................407login() ..................................................................................................................................408credentials(**kwargs) ..........................................................................................................408APIRequestFactory vs. APIClient ...............................................................................................411Using factory_boy .....................................................................................................................412Mocking External Dependencies ...............................................................................................420How to Use Patch ................................................................................................................421RequestsClient ..........................................................................................................................429Headers and Authentication ................................................................................................430CSRF Handling .....................................................................................................................431When to Use ........................................................................................................................431CoreAPIClient ............................................................................................................................432Headers and Authentication ................................................................................................433CSRF Tokens (Session Authentication) ................................................................................433Dynamic Discovery ..............................................................................................................434Comparison with RequestsClient ........................................................................................434When to Use ........................................................................................................................435Chapter 17:
Documenting APIs .............................................................................437Preparing for This Chapter ........................................................................................................437drf-spectacular .........................................................................................................................439Customization by Using @extend_schema .........................................................................444drf-yasg ....................................................................................................................................450
Index .....................................................................................................................455