Django REST APIs Demystified: Simplifying API Development with Django

Django REST APIs Demystified: Simplifying API Development with Django

Django REST APIs Demystified: Simplifying API Development with Django
Автор: Patil Ganeshkumar
Дата выхода: 2025
Издательство: Apress Media, LLC.
Количество страниц: 479
Размер файла: 1,9 МБ
Тип файла: PDF
Добавил: codelibs
 Проверить на вирусы  Дополнительные материалы 

Table of Contents....5

About the Author....13

About the Technical Reviewer....14

Acknowledgments....15

Introduction....16

Chapter 1: Introduction to APIs....18

Private API....19

Public API....19

Partner API....19

RESTful APIs (Representational State Transfer)....20

SOAP APIs (Simple Object Access Protocol)....20

GraphQL APIs....20

JSON-RPC and XML-RPC APIs....21

WebSocket APIs....21

gRPC APIs....21

Chapter 2: REST API Concepts....22

Web APIs....22

Endpoint....22

HTTP Methods....23

GET Method....23

POST Method....23

PUT Method....24

PATCH Method....24

DELETE Method....24

Other Methods....25

HTTP Request....25

HTTP Response....26

Request Parameters....27

Chapter 3: Project Configuration....29

Environment....29

Project Overview....30

Project Setup....30

Chapter 4: Django REST Framework....35

Serialization and Deserialization....35

Viewsets and Serializers....35

Authentication and Permissions....36

URL Routing and View Dispatching....36

Request/Response Handling....36

Pagination and Filtering....36

Content Negotiation....36

Testing and Documentation....37

Why Django REST Framework....37

Chapter 5: Postman....39

Why Use Postman?....39

Chapter 6: Serializers and Views....41

Using Serializer Fields....41

Preparing for This Chapter....42

Create a Serializer....43

Views....44

Class-Based Views....44

Function-Based Views....45

Implement Class-Based View for the Project....45

Serializer Advanced Concepts....47

Nested Serializer....47

Relational Fields....48

PrimaryKeyRelatedField....48

StringRelatedField....51

HyperlinkedRelatedField....52

HyperlinkedIdentityField....54

Difference Between HyperlinkedRelatedField and Hyperlinked IdentityField....55

SlugRelatedField....56

Create a New Object....57

Serializer Validation....59

Field-Level Validation....60

Object-Level Validation....61

Get a Single Object....61

Update an Object....63

Delete an Object....66

Status Code....67

HTTP_100_CONTINUE....68

HTTP_101_SWITCHING_PROTOCOLS....68

HTTP_200_OK....68

HTTP_201_CREATED....68

HTTP_202_ACCEPTED....69

HTTP_203_NON_AUTHORITATIVE_INFORMATION....69

HTTP_204_NO_CONTENT....70

HTTP_205_RESET_CONTENT....70

HTTP_206_PARTIAL_CONTENT....70

HTTP_300_MULTIPLE_CHOICES....71

HTTP_301_MOVED_PERMANENTLY....72

HTTP_302_FOUND....72

HTTP_303_SEE_OTHER....72

HTTP_304_NOT_MODIFIED....73

HTTP_305_USE_PROXY....74

HTTP_306_RESERVED....74

HTTP_307_TEMPORARY_REDIRECT....74

HTTP_308_PERMANENT_REDIRECT....75

HTTP_400_BAD_REQUEST....76

HTTP_401_UNAUTHORIZED....76

HTTP_402_PAYMENT_REQUIRED....76

HTTP_403_FORBIDDEN....77

HTTP_404_NOT_FOUND....77

HTTP_405_METHOD_NOT_ALLOWED....77

HTTP_406_NOT_ACCEPTABLE....78

HTTP_407_PROXY_AUTHENTICATION_REQUIRED....78

HTTP_408_REQUEST_TIMEOUT....78

HTTP_409_CONFLICT....79

HTTP_410_GONE....80

HTTP_411_LENGTH_REQUIRED....80

HTTP_412_PRECONDITION_FAILED....81

HTTP_413_REQUEST_ENTITY_TOO_LARGE....82

HTTP_414_REQUEST_URI_TOO_LONG....82

HTTP_415_UNSUPPORTED_MEDIA_TYPE....83

HTTP_416_REQUESTED_RANGE_NOT_SATISFIABLE....83

HTTP_417_EXPECTATION_FAILED....84

HTTP_422_UNPROCESSABLE_ENTITY....84

HTTP_423_LOCKED....84

HTTP_424_FAILED_DEPENDENCY....85

HTTP_426_UPGRADE_REQUIRED....86

HTTP_428_PRECONDITION_REQUIRED....86

HTTP_429_TOO_MANY_REQUESTS....86

HTTP_431_REQUEST_HEADER_FIELDS_TOO_LARGE....87

HTTP_451_UNAVAILABLE_FOR_LEGAL_REASONS....87

HTTP_500_INTERNAL_SERVER_ERROR....88

HTTP_501_NOT_IMPLEMENTED....88

HTTP_502_BAD_GATEWAY....88

HTTP_503_SERVICE_UNAVAILABLE....89

HTTP_504_GATEWAY_TIMEOUT....89

HTTP_505_HTTP_VERSION_NOT_SUPPORTED....89

HTTP_506_VARIANT_ALSO_NEGOTIATES....90

HTTP_507_INSUFFICIENT_STORAGE....90

HTTP_508_LOOP_DETECTED....90

HTTP_510_NOT_EXTENDED....91

HTTP_511_NETWORK_AUTHENTICATION_REQUIRED....91

ModelSerializer....92

Specifying Which Fields to Include....96

Specifying Nested Serialization....96

Specifying Fields Explicitly....100

Specifying Read-Only Fields....100

Additional Keyword Arguments....101

Customizing Field Mappings....102

The field_class and field_kwargs API....106

HyperlinkedModelSerializer....110

ListSerializer....116

BaseSerializer....121

Advanced Serializer Usage....128

Serializer Context....128

Source Keyword....129

Serializers Initial Data....131

Generic Views....132

GenericAPIView....133

Attributes....134

Methods....135

Other Methods....142

Mixins....144

Use of Mixins....144

ListModelMixin....145

CreateModelMixin....145

RetrieveModelMixin....147

UpdateModelMixin....148

DestroyModelMixin....150

Save and Deletion Hooks....151

Concrete View Classes....152

CreateAPIView....153

ListAPIView....155

RetrieveAPIView....156

DestroyAPIView....158

UpdateAPIView....160

ListCreateAPIView....162

RetrieveUpdateAPIView....163

RetrieveDestroyAPIView....163

RetrieveUpdateDestroyAPIView....164

Customizing the Generic Views....165

Creating Custom Mixins....166

Creating Custom Base Classes....169

Chapter 7: ViewsSets and Routers....173

Preparing for This Chapter....175

ViewSet....177

GenericViewSet....181

ModelViewSet....183

ReadOnlyModelViewSet....185

Routers....187

Routing for Extra Actions....193

Routing Additional HTTP Methods for Extra Actions....196

Custom Routers....198

Chapter 8: Validators....203

Validation in REST Framework....205

UniqueValidator....208

UniqueTogetherValidator....209

Unique Date/Month/Year Validator....210

Writing Custom Validators....211

Preparing for This Chapter....211

Chapter 9: Authentication....219

How Authentication Is Determined....220

Setting the Authentication Scheme....222

Unauthorized and Forbidden Responses....223

Preparing for This Chapter....225

API Reference....228

BasicAuthentication....229

TokenAuthentication....232

Generating Tokens....234

By Using Signals....234

By Exposing an API Endpoint....238

With Django Admin....241

Using the Django manage.py Command....241

SessionAuthentication....247

RemoteUserAuthentication....248

Custom Authentication....250

When to Use Custom Authentication....253

Benefits of Custom Authentication....253

Chapter 10: Permissions....254

Default User Permissions....258

Permissions Without App Label (Global Permissions)....259

Permissions with App Label (Model-Specific Permissions)....259

How Permissions Are Determined....260

View-Level Permission Checks....260

Object-Level Permission Checks (Optional)....261

Permission Evaluation Key Points....262

Preparing for This Chapter....263

Setting the Permission Policy....265

Built-In Classes....267

AllowAny....268

IsAuthenticated....269

IsAuthenticatedOrReadOnly....269

IsAdminUser....270

DjangoModelPermissions....271

DjangoModelPermissionsOrAnonReadOnly....276

DjangoObjectPermissions....276

Installing django-guardian....277

Using DjangoObjectPermissions....278

Custom Permissions....283

Access Restriction Methods....287

Chapter 11: Caching....289

Preparing for This Chapter....289

View-Level Caching....291

How View-Level Caching Works....291

Applying the @cache_page Decorator....292

1) Class-Based View Example....292

2) Function-Based View Example....293

Low-Level Caching (Custom Caching in Views or Functions)....294

Limitations and Considerations....296

Cache Invalidation....297

DRF Cache Mixins....297

vary_on_headers....299

Additional Notes....300

vary_on_cookie....301

Additional Notes....302

Chapter 12: Throttling....303

Why Use Throttling?....304

Types of Throttling in DRF....305

AnonRateThrottle....305

Key Features of AnonRateThrottle....305

Example Scenario....307

UserRateThrottle....307

Key Features of UserRateThrottle....307

Example Scenario....309

ScopedRateThrottle....310

How ScopedRateThrottle Works....310

Example Explanation....310

Use Cases....311

Practical Benefits....312

Preparing for This Chapter....312

How Throttling Is Determined....314

How Clients Are Identified....314

Setting Up the Cache....315

Cache Back End in DRF....316

Example of Custom Throttle Class with Custom Cache....316

Configuring the Cache in settings.py....317

Setting Up Throttling in DRF....318

Custom Throttling....321

Explanation of the Methods....321

A Note on Concurrency....325

Guaranteeing the Number of Requests....325

Example of a More Robust Custom Throttle....325

Chapter 13: Filtering, Searching, and Ordering....327

Preparing for This Chapter....327

Filtering Against the Current User....329

Filtering Against the URL....331

Filtering Against Query Parameters....333

Generic Filtering....335

Overriding the Initial queryset....337

API Guide....339

DjangoFilterBackend....339

How DjangoFilterBackend Works....339

SearchFilter....340

How the SearchFilter Works....341

Default Search Behavior....342

Prefixing Field Names to Modify Search Behavior....343

Overriding the Default Search Parameter....344

Dynamically Changing Search Fields....346

OrderingFilter....347

How OrderingFilter Works....347

Specifying Which Fields May Be Ordered Against....349

Specifying a Default Ordering....350

Custom Generic Filtering....352

Customizing the Interface....354

Chapter 14: Pagination....357

Why Use Pagination?....357

How Pagination Works in DRF....359

Preparing for This Chapter....359

Default Pagination Classes in DRF....361

PageNumberPagination....361

Configure Global Pagination Settings....362

django_paginator_class....363

page_size....363

page_query_param....364

max_page_size....364

last_page_strings....364

Template....364

LimitOffsetPagination....366

Setup: Enabling LimitOffsetPagination Globally....366

Per-View Configuration....367

default_limit....367

limit_query_param....367

offset_query_param....367

max_limit....368

Template....368

CursorPagination....370

Details and Limitations....370

Set Up: Global Configuration....371

Set Up: Per-View Configuration....372

page_size....372

cursor_query_param....372

Ordering....372

Template....373

Custom Pagination Styles....376

Chapter 15: Versioning....385

Versioning with REST Framework....385

Configuring the Versioning Scheme....387

Global Configuration....387

Per-View Configuration....388

Customizing the Versioning Class....388

Preparing for This Chapter....389

Types of API Versioning....391

URLPathVersioning....391

NamespaceVersioning....394

How URLs Work with NamespaceVersioning....395

NamespaceVersioning vs. URLPathVersioning....398

QueryParameterVersioning....399

AcceptHeaderVersioning....402

HostNameVersioning....405

Custom Versioning Schemes....406

Chapter 16: Testing....411

Preparing for This Chapter....412

APIRequestFactory....413

Format Argument....414

PUT and PATCH with Form Data....415

Forcing Authentication....415

CSRF Validation....416

APIClient....421

login()....422

credentials(**kwargs)....422

APIRequestFactory vs. APIClient....425

Using factory_boy....426

Mocking External Dependencies....434

How to Use Patch....435

RequestsClient....443

Headers and Authentication....444

CSRF Handling....445

When to Use....445

CoreAPIClient....446

Headers and Authentication....447

CSRF Tokens (Session Authentication)....447

Dynamic Discovery....448

Comparison with RequestsClient....448

When to Use....449

Chapter 17: Documenting APIs....450

Preparing for This Chapter....450

drf-spectacular....452

Customization by Using @extend_schema....457

drf-yasg....463

Index....468

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


Похожее:

Список отзывов:

Нет отзывов к книге.