### Defining Schema Examples with Classmethods Source: https://github.com/royhzq/djagger/blob/main/docs/source/user_guide.md Set examples for request bodies and responses by defining a classmethod named 'example' within your Pydantic schema. This method should return an instance of the schema with predefined values. This ensures that examples are validated against the schema, promoting data integrity. ```python from pydantic import BaseModel as Schema from rest_framework.views import APIView class UserSchema(Schema): """A User object""" id : int username : str firstName : str lastName : str email : str password : str phone : str userStatus : int @classmethod def example(cls): return cls( id=10, username="theUser", firstName="John", lastName="James", email="john@email.com", password="12345", phone="12345", userStatus=4 ) class CreateUserAPI(APIView): """This can only be done by the logged in user.""" summary = "Create user" request_schema = UserSchema response_schema = UserSchema def post(self, request): ... return Response({}) ``` -------------------------------- ### Providing Examples for Parameters with Pydantic Field Source: https://github.com/royhzq/djagger/blob/main/docs/source/user_guide.md Examples for path, query, header, and cookie parameters can be specified directly within the `Field` definition using the `example` argument. This is a concise way to document individual parameters and their expected values. ```python from pydantic import BaseModel as Schema, Field class ArticleYearSchema(Schema): year : int = Field(required=True, example="2009") ``` -------------------------------- ### Example GET Endpoint Documentation with Djagger Source: https://github.com/royhzq/djagger/blob/main/docs/source/getting_started.md Demonstrates creating a GET endpoint in Django using Djagger. It defines a Pydantic schema for the response and associates it with a Django REST Framework APIView. ```python from rest_framework.views import APIView from rest_framework.response import Response from pydantic import BaseModel as Schema import datetime class ArticleDetailSchema(Schema): created : datetime.datetime title : str author : str content : str class RandomArticleAPI(APIView): """Return a random article from the Blog""" response_schema = ArticleDetailSchema def get(self, request): ... return Response({}) ``` -------------------------------- ### Djagger Python API View Example Source: https://github.com/royhzq/djagger/blob/main/docs/source/user_guide.md This Python code demonstrates how to define API views using Djagger's conventions. It shows how to specify HTTP method-specific attributes like summary, path parameters, request schemas, and response schemas for GET, POST, and DELETE operations on a 'Toy' resource. This allows for detailed OpenAPI documentation generation. ```python class FindToyByIdAPI(APIView): get_summary = "Find Toy by ID" get_path_params = ToyIdSchema get_response_schema = { "200":ToySchema, "400":InvalidToySchema, "404":ToyNotFoundSchema } post_summary = "Update Toy with form data" post_request_schema = { "multipart/form-data":ToyIdFormSchema } post_response_schema = { "405":InvalidToySchema } delete_summary = "Deletes a Toy" delete_header_params = ToyDeleteHeaderSchema delete_path_params = ToyIdSchema delete_response_schema = { "400":InvalidToySchema } def get(self, request, toyId: int): ... return Response({}) def post(self, request, toyId: int): ... return Response({}) def delete(self, request, toyId: int): ... return Response({}) ``` -------------------------------- ### Install and Configure Djagger in Django Source: https://context7.com/royhzq/djagger/llms.txt This snippet shows how to install Djagger via pip, add it to Django's INSTALLED_APPS, configure project-wide documentation settings in settings.py, and include Djagger's URLs for serving documentation and schema. ```python # Install via pip # pip install djagger # settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'djagger', # Add djagger to your installed apps ] # Configure documentation settings DJAGGER_DOCUMENT = { "version": "1.0.0", "title": "My API Documentation", "description": "Comprehensive API documentation for my Django project", "license_name": "MIT", "app_names": ['myapp', 'auth_app'], # Apps to document "tags": [ {'name': 'myapp', 'description': 'Main application endpoints'}, {'name': 'auth_app', 'description': 'Authentication endpoints'}, ], "servers": [ {"url": "https://api.example.com", "description": "Production server"}, {"url": "http://localhost:8000", "description": "Development server"} ], } # urls.py from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('djagger/', include('djagger.urls')), # Serves docs at /djagger/api/docs # Your other URL patterns... ] # Access documentation at: http://localhost:8000/djagger/api/docs # Access JSON schema at: http://localhost:8000/djagger/schema.json ``` -------------------------------- ### Install Djagger using pip Source: https://github.com/royhzq/djagger/blob/main/docs/source/getting_started.md Install the Djagger package using pip. This command downloads and installs the latest version of Djagger and its dependencies. ```bash pip install djagger ``` -------------------------------- ### Documenting Multiple Response Schemas with Dictionary in Python Source: https://github.com/royhzq/djagger/blob/main/docs/source/user_guide.md This example demonstrates how to document multiple possible responses for an API endpoint using a dictionary for `response_schema`. Different HTTP status codes (e.g., '200', '400', '403') can be mapped to their respective Pydantic schemas. It also shows how to specify a custom content type for a particular response, like ('403', 'text/plain'). ```python class Login(APIView): summary = "Logs user into the system" query_params = LoginRequestSchema response_schema = { "200":LoginSuccessSchema, "400":LoginErrorSchema, ("403", "text/plain"): ForbiddenSchema } def get(self, request): ... return Response({}) ``` -------------------------------- ### GET /user/login Source: https://github.com/royhzq/djagger/blob/main/docs/source/user_guide.md Logs a user into the system. Supports various response types including success, error, and forbidden. ```APIDOC ## GET /user/login ### Description Authenticates a user and logs them into the system. This endpoint handles successful logins, authentication errors, and forbidden access scenarios. ### Method GET ### Endpoint /user/login ### Parameters #### Query Parameters - **username** (str) - Required - The user's username. - **password** (str) - Required - The user's password. ### Request Example ``` /user/login?username=testuser&password=password123 ``` ### Response #### Success Response (200) - **token** (str) - Authentication token for the logged-in user. #### Error Response (400) - **error** (str) - Description of the authentication error. #### Forbidden Response (403) - **message** (str) - Message indicating forbidden access. #### Response Example (200) ```json { "token": "your_auth_token_here" } ``` #### Response Example (400) ```json { "error": "Invalid username or password." } ``` #### Response Example (403) ```json { "message": "Access denied." } ``` ``` -------------------------------- ### Set Schema Examples from Callable Source: https://github.com/royhzq/djagger/blob/main/docs/source/api.md Checks if a class has a callable `example()` method and sets the 'example' field in a given schema to the result of this method. The callable must return an instance of the pydantic base model type. ```python from typing import Any, Dict def schema_set_examples(schema: Dict, model: Any): # Implementation details here pass ``` -------------------------------- ### Toy API Endpoints Source: https://github.com/royhzq/djagger/blob/main/docs/source/user_guide.md Documentation for the Toy API, including operations for finding, updating, and deleting toys. ```APIDOC ## GET /toy/{toyId} ### Description Finds a Toy by its unique identifier. ### Method GET ### Endpoint /toy/{toyId} ### Parameters #### Path Parameters - **toyId** (int) - Required - The unique identifier of the toy to retrieve. ### Request Example (No request body for GET request) ### Response #### Success Response (200) - **ToySchema** - Contains the details of the requested toy. #### Response Example (Example response body based on ToySchema) ## POST /toy/{toyId} ### Description Updates a Toy using form data. ### Method POST ### Endpoint /toy/{toyId} ### Parameters #### Path Parameters - **toyId** (int) - Required - The unique identifier of the toy to update. #### Request Body - **ToyIdFormSchema** (multipart/form-data) - Required - Form data for updating the toy. ### Request Example (Example request body for multipart/form-data) ### Response #### Success Response (200) (No specific schema mentioned for success, assumes generic success response) #### Error Response (405) - **InvalidToySchema** - Indicates an invalid toy request. #### Response Example (Example response body based on InvalidToySchema for 405 error) ## DELETE /toy/{toyId} ### Description Deletes a Toy. ### Method DELETE ### Endpoint /toy/{toyId} ### Parameters #### Path Parameters - **toyId** (int) - Required - The unique identifier of the toy to delete. #### Header Parameters - **ToyDeleteHeaderSchema** - Schema for delete header parameters. ### Request Example (Example request with specified headers) ### Response #### Success Response (200) (No specific schema mentioned for success, assumes generic success response) #### Error Response (400) - **InvalidToySchema** - Indicates an invalid toy request. #### Response Example (Example response body based on InvalidToySchema for 400 error) ``` -------------------------------- ### POST /blog/articles/create Source: https://github.com/royhzq/djagger/blob/main/docs/source/user_guide.md API endpoint for creating a blog article. It accepts a title and content in the request body and returns the created article details. ```APIDOC ## POST /blog/articles/create ### Description Creates a new blog article with the provided title and content. ### Method POST ### Endpoint /blog/articles/create ### Parameters #### Request Body - **title** (str) - Required - Title of the blog article. - **content** (str) - Required - Content of the blog article. ### Request Example ```json { "title": "My First Blog Post", "content": "This is the content of my first blog post." } ``` ### Response #### Success Response (200) - **created** (datetime) - Timestamp of article creation. - **title** (str) - The title of the article. - **author** (str) - The author of the article. - **content** (str) - The content of the article. #### Response Example ```json { "created": "2023-10-27T10:00:00Z", "title": "My First Blog Post", "author": "John Doe", "content": "This is the content of my first blog post." } ``` ``` -------------------------------- ### Customizing Request Body Media Types with Dictionary in Python Source: https://github.com/royhzq/djagger/blob/main/docs/source/user_guide.md This example shows how to specify custom media types for the request body using a dictionary with Djagger. Instead of a single schema, a dictionary maps media types (e.g., 'application/octet-stream') to their respective Pydantic schemas. This is useful when an endpoint accepts different content types for its request body, such as binary data. ```python from pydantic import BaseModel as Schema, Field from rest_framework.views import APIView class ToyUploadImageSchema(Schema): """Example values are not available for application/octet-stream media types.""" ... __root__ : bytes class UploadImageAPI(APIView): summary = "Uploads an image" path_params = ToyIdSchema query_params = ToyMetaDataSchema request_schema = { "application/octet-stream": ToyUploadImageSchema } response_schema = ToyUploadImageSuccessSchema def post(self, request, toyId: int): return Response({}) ``` -------------------------------- ### Example POST Endpoint Documentation with Djagger Source: https://github.com/royhzq/djagger/blob/main/docs/source/getting_started.md Illustrates creating a POST endpoint with Djagger. It defines Pydantic schemas for both the request and response, associating them with a Django REST Framework APIView for validation and documentation. ```python from rest_framework.views import APIView from rest_framework.response import Response from pydantic import BaseModel as Schema, Field import datetime class ArticleDetailSchema(Schema): created : datetime.datetime title : str author : str content : str class ArticleCreateSchema(Schema): """POST schema for blog article creation""" title : str = Field(description="Title of Blog article") content : str = Field(description="Blog article content") class ArticleCreateAPI(APIView): request_schema = ArticleCreateSchema response_schema = ArticleDetailSchema def post(self, request): ... return Response({}) ``` -------------------------------- ### GET /toys/findByStatus Source: https://context7.com/royhzq/djagger/llms.txt Find toys by their status. Allows filtering of toys based on the 'available', 'pending', or 'sold' status. ```APIDOC ## GET /toys/findByStatus ### Description Find toys by status with filtering. This endpoint allows you to retrieve a list of toys filtered by their availability status. ### Method GET ### Endpoint /toys/findByStatus ### Parameters #### Query Parameters - **status** (string) - Optional - Filter toys by status (enum: available, pending, sold) (default: available) ### Request Example ```json { "status": "available" } ``` ### Response #### Success Response (200) - **__root__** (array) - Array of toy objects - **items** (object) - **id** (integer) - Optional - Unique toy identifier - **name** (string) - Required - Toy name (min_length: 1, max_length: 100) - **category** (object) - Optional - Toy category information - **id** (integer) - Required - Category ID - **name** (string) - Required - Category name - **description** (string) - Optional - Category description - **photoUrls** (array) - Required - URLs of toy photos - **items** (string) - **tags** (array) - Optional - Associated tags - **items** (object) - **id** (integer) - Required - Tag ID - **name** (string) - Required - Tag name - **color** (string) - Required - Hex color code (pattern: `^#[0-9A-Fa-f]{6}$`) - **status** (string) - Optional - Toy status (enum: available, pending, sold) (default: available) - **price** (number) - Required - Price in USD (gt: 0) - **stock_quantity** (integer) - Required - Available stock (ge: 0) #### Response Example ```json [ { "id": 12345, "name": "Robot Transformer Deluxe", "category": { "id": 1, "name": "Action Figures", "description": "Collectible action figures and toys" }, "photoUrls": [ "https://example.com/photos/robot1.jpg", "https://example.com/photos/robot2.jpg" ], "tags": [ { "id": 1, "name": "robots", "color": "#FF5733" }, { "id": 2, "name": "transformers", "color": "#33FF57" } ], "status": "available", "price": 49.99, "stock_quantity": 150 }, { "id": 12346, "name": "Spaceship Model Kit", "photoUrls": [ "https://example.com/photos/spaceship.jpg" ], "status": "available", "price": 79.99, "stock_quantity": 75 } ] ``` ``` -------------------------------- ### POST /toy/{toyId}/uploadImage Source: https://github.com/royhzq/djagger/blob/main/docs/source/user_guide.md Uploads an image for a specific toy. Supports custom media types and schemas. ```APIDOC ## POST /toy/{toyId}/uploadImage ### Description Uploads an image associated with a specific toy, allowing for custom media types and metadata. ### Method POST ### Endpoint /toy/{toyId}/uploadImage ### Parameters #### Path Parameters - **toyId** (int) - Required - The ID of the toy. #### Query Parameters - **metadata** (object) - Optional - Metadata for the uploaded image. #### Request Body - **bytes** - Required - The image data in octet-stream format. ### Request Example (No JSON example available for octet-stream) ### Response #### Success Response (200) - **message** (str) - A success message indicating the image was uploaded. #### Response Example ```json { "message": "Image uploaded successfully." } ``` ``` -------------------------------- ### Documenting API Response Schema with Pydantic Source: https://github.com/royhzq/djagger/blob/main/docs/source/user_guide.md Demonstrates how to document API responses using Pydantic's BaseModel, aliased as Schema. It shows how docstrings are used for schema descriptions and how to define fields with types, optionality, default values, and custom descriptions using `Field`. ```python from pydantic import BaseModel as Schema, Field from typing import Optional class MyResponse(Schema): """This docstring will be used to describe the response""" name : str age : int remarks : Optional[str] email : str = Field("default@example.com", description="This is a description of the field) ``` -------------------------------- ### Document Function-Based Views with Djagger Decorator Source: https://github.com/royhzq/djagger/blob/main/docs/source/user_guide.md Demonstrates how to document Django function-based views using Djagger's `@schema` decorator. This decorator allows specifying HTTP methods, summaries, and request/response schemas. ```python from pydantic import BaseModel as Schema from djagger.decorators import schema from typing import List class AuthorSchema(Schema): first_name : str last_name : str class AuthorListSchema(Schema): authors : List[AuthorSchema] @schema( methods=['GET', 'POST'], get_summary="List Authors", get_response_schema=AuthorListSchema, post_summary="Create Author", post_request_schema=AuthorSchema, post_response_schema=AuthorSchema, ) def author_api(request): """API to create an author or list all authors""" if request.method == 'get': ... return Response({}) if request.method == 'post': ... return Response({}) ``` -------------------------------- ### GET /articles/year/{year} Source: https://context7.com/royhzq/djagger/llms.txt Retrieves a list of articles for a specific year, with support for pagination and authentication via headers and cookies. ```APIDOC ## GET /articles/year/{year} ### Description Lists all articles for a given year with pagination. Requires an API key in the header and a session ID cookie for authentication. ### Method GET ### Endpoint /articles/year/{year} ### Parameters #### Path Parameters - **year** (integer) - Required - Year to filter articles (e.g., 2023) #### Query Parameters - **page** (integer) - Optional - Page number, defaults to 1, minimum value is 1. - **page_size** (integer) - Optional - Items per page, defaults to 10, maximum value is 100. #### Header Parameters - **api_key** (string) - Required - API authentication key #### Cookie Parameters - **session_id** (string) - Required - User session identifier ### Response #### Success Response (200) - **year** (integer) - The year for which articles are listed. - **page** (integer) - The current page number. - **results** (array) - A list of articles matching the criteria. #### Response Example ```json { "year": 2023, "page": 1, "results": [ { "id": 1, "title": "Article One", "content": "Content of article one." }, { "id": 2, "title": "Article Two", "content": "Content of article two." } ] } ``` ``` -------------------------------- ### Function-Based Views (FBV) Source: https://github.com/royhzq/djagger/blob/main/docs/source/user_guide.md Document function-based views using the `@schema` decorator, specifying handled HTTP methods and providing schema definitions for requests and responses. ```APIDOC ## Function-Based Views (FBV) ### Description Document function-based views by applying the `@schema` decorator. This decorator requires a `methods` argument, which is a list of strings representing the HTTP methods the view handles. Additional arguments can be passed to the decorator, mirroring the attributes used for class-based views. ### Method GET, POST ### Endpoint `/blog/author` (Inferred from example) ### Parameters #### Query Parameters None specified in the example. #### Request Body For POST requests, the request body should conform to `AuthorSchema`. - **first_name** (str) - Required - First name of the author. - **last_name** (str) - Required - Last name of the author. ### Request Example ```json { "first_name": "string", "last_name": "string" } ``` ### Response #### Success Response (200) For GET requests, the response body will be `AuthorListSchema`. - **authors** (List[AuthorSchema]) - A list of author objects. For POST requests, the response body will be `AuthorSchema`. - **first_name** (str) - First name of the author. - **last_name** (str) - Last name of the author. #### Response Example For GET requests: ```json { "authors": [ { "first_name": "string", "last_name": "string" } ] } ``` For POST requests: ```json { "first_name": "string", "last_name": "string" } ``` ``` -------------------------------- ### Documenting Request Parameters Source: https://github.com/royhzq/djagger/blob/main/docs/source/user_guide.md Djagger allows documentation of various request parameter types including path, query, header, cookie, and request body directly within Django views using specific attributes. ```APIDOC ## Documenting Request Parameters ### Description Djagger enables the documentation of various request parameter types directly within Django views by assigning Pydantic models to specific attributes. These attributes define the expected structure and types for each parameter category. ### Parameter Types: - **Path Parameters**: Part of the URL path (e.g., `/article/`). Documented using `path_params` or `_path_params`. - **Query Parameters**: Appended to the URL (e.g., `/articles?page=3`). Documented using `query_params` or `_query_params`. - **Header Parameters**: Custom headers expected in the request. Documented using `header_params` or `_header_params`. - **Cookie Parameters**: Specific cookie values required for the API. Documented using `cookie_params` or `_cookie_params`. - **Request Body**: HTTP body data for methods like POST, PUT, UPDATE. Documented using `request_schema` or `_request_schema`. ### Example Implementation ```python from pydantic import BaseModel as Schema, Field from rest_framework.views import APIView from rest_framework.response import Response from .schema import ListArticleDetailSchema # Assuming this schema is defined elsewhere class ArticleYearSchema(Schema): year : int = Field(required=True) class ArticlePageSchema(Schema): page : int class ArticleHeaderSchema(Schema): api_key : str class ArticleCookieSchema(Schema): username : str class ArticlesYearAPI(APIView): """List all articles given a year""" path_params = ArticleYearSchema query_params = ArticlePageSchema header_params = ArticleHeaderSchema cookie_params = ArticleCookieSchema response_schema = ListArticleDetailSchema # Schema for the response def get(self, request): # Your view logic here return Response({}) ``` ### Generated Documentation Links: - [Example Docs](https://djagger-example.netlify.app/#tag/Blog/paths/~1blog~1articles~1{year}~1/get) - [Example Code](https://github.com/royhzq/djagger-example/blob/7293a78388498ec6d9fc74c6b299bfc16374bf57/Blog/views.py#L72) ``` -------------------------------- ### Documenting Request Parameters in Django Views Source: https://github.com/royhzq/djagger/blob/main/docs/source/user_guide.md Illustrates how to document various request parameters (path, query, header, cookie) for a Django API view using Pydantic schemas. It shows the use of attributes like `path_params`, `query_params`, `header_params`, and `cookie_params` within an `APIView` subclass. ```python from pydantic import BaseModel as Schema, Field from rest_framework.views import APIView from rest_framework.response import Response from .schema import ListArticleDetailSchema class ArticleYearSchema(Schema): year : int = Field(required=True) class ArticlePageSchema(Schema): page : int class ArticleHeaderSchema(Schema): api_key : str class ArticleCookieSchema(Schema): username : str class ArticlesYearAPI(APIView): """List all articles given a year""" path_params = ArticleYearSchema query_params = ArticlePageSchema header_params = ArticleHeaderSchema cookie_params = ArticleCookieSchema response_schema = ListArticleDetailSchema def get(self, request): ... return Response({}) ``` -------------------------------- ### Djagger Attributes Source: https://github.com/royhzq/djagger/blob/main/docs/source/user_guide.md This section outlines the various attributes available in Djagger for defining API endpoints and their documentation. ```APIDOC ## Djagger Attributes This section details the attributes used by Djagger to define API endpoint behavior and documentation. ### Attribute Details: - **path_params** - **Type**: `pydantic.main.ModelMetaclass` or `rest_framework.serializers.SerializerMetaclass` - **Description**: Defines the schema for parameter values that are part of the URL path (e.g., `/article/`). - **query_params** - **Type**: `pydantic.main.ModelMetaclass` or `rest_framework.serializers.SerializerMetaclass` - **Description**: Defines the schema for parameter values appended to the URL as query parameters (e.g., `/articles?page=3`). - **header_params** - **Type**: `pydantic.main.ModelMetaclass` or `rest_framework.serializers.SerializerMetaclass` - **Description**: Defines the schema for custom headers expected in the request. - **cookie_params** - **Type**: `pydantic.main.ModelMetaclass` or `rest_framework.serializers.SerializerMetaclass` - **Description**: Defines the schema for API-specific cookie values. - **request_schema** - **Type**: `pydantic.main.ModelMetaclass` or `rest_framework.serializers.SerializerMetaclass` (can be a dictionary mapping media types to schemas). - **Description**: Defines the schema for the HTTP request body data, commonly used for POST, PUT, and UPDATE methods. - **response_schema** - **Type**: `pydantic.main.ModelMetaclass` or `rest_framework.serializers.SerializerMetaclass` (can be a dictionary mapping HTTP status codes to schemas). - **Description**: Defines the schema for responses returned by the API. By default, if a Pydantic model or DRF serializer is provided, it's documented as a 200 OK response. - **summary** - **Type**: `str` - **Description**: A summary of the API endpoint. Defaults to the view's `__name__` if not specified. - **tags** - **Type**: `List[str]` - **Description**: A list of string tag names for categorizing the API. - **description** - **Type**: `str` - **Description**: A detailed description of the API endpoint. Defaults to the view's docstring if not specified. ### Hierarchy of Specificity A more specific declaration of a Djagger view attribute will override a less specific one. For example, `summary` and `post_summary` attributes result in the POST endpoint using `post_summary` while other endpoints use the general `summary` value. ``` -------------------------------- ### List URLs from Resolver Source: https://github.com/royhzq/djagger/blob/main/docs/source/api.md Generates a list of tuples, where each tuple contains a cleaned full URL path and its corresponding URLPattern object, starting from a given URL resolver. ```python from django.urls import URLPattern, URLResolver from typing import List, Tuple def list_urls(resolver: URLResolver, prefix: str = '') -> List[Tuple[str, URLPattern]]: # Implementation details here pass ``` -------------------------------- ### Document Generic Views with Djagger Source: https://github.com/royhzq/djagger/blob/main/docs/source/user_guide.md Shows how to document Django generic views with Djagger. Djagger automatically uses the `serializer_class` as `response_schema` for generic views, but it can be overridden. Documentation follows the same pattern as class-based views. ```python class CategoryList(generics.ListCreateAPIView): """Example Generic View Documentation""" serializer_class = CategorySerializer(many=True) get_summary = "Category List" post_summary = "Category List Create" def list(self, request): ... return Response({}) def create(self, request): ... return Response({}) ``` -------------------------------- ### Security Schemes Configuration Source: https://github.com/royhzq/djagger/blob/main/docs/source/user_guide.md Configure security schemes in your Django settings to define authentication methods for your API. These schemes can be referenced by your API endpoints. ```APIDOC ## Security Schemes Configuration ### Description Define various security schemes (e.g., HTTP Basic, JWT Bearer) within the `DJAGGER_DOCUMENT` settings. These schemes are then available for use in documenting your API endpoints. ### Configuration Add or modify the `components.securitySchemes` dictionary in your `settings.py`. ```python DJAGGER_DOCUMENT = { ... "components": { "securitySchemes": { "http": { "type": "http", "scheme": "basic" }, "jwt": { "type": "http", "scheme": "bearer", "bearerFormat": "JWT" } } } ... } ``` ### Usage in API Views Document API views using the `security` attribute, referencing the defined scheme names. ```python from rest_framework.views import APIView from rest_framework.response import Response class PlaceOrderAPI(APIView): summary = "Place an order for a toy" security = [ {"http": []} ] def post(self, request): # ... order placement logic ... return Response({}) ``` ``` -------------------------------- ### Document Django REST Framework View with Response Schema Source: https://context7.com/royhzq/djagger/llms.txt This example demonstrates documenting a Django REST Framework APIView by defining a pydantic model for the response schema and assigning it to the `response_schema` attribute of the view. This automatically generates OpenAPI documentation for the response structure. ```python from rest_framework.views import APIView from rest_framework.response import Response from pydantic import BaseModel as Schema import datetime class ArticleDetailSchema(Schema): """Detailed article information returned by the API""" created: datetime.datetime title: str author: str content: str class RandomArticleAPI(APIView): """Return a random article from the Blog""" response_schema = ArticleDetailSchema tags = ['Blog'] # Optional: group this endpoint under 'Blog' tag def get(self, request): # Your business logic here article_data = { 'created': datetime.datetime.now(), 'title': 'Sample Article', 'author': 'John Doe', 'content': 'This is the article content...' } return Response(article_data) # This generates OpenAPI documentation showing: # - Endpoint: GET /path/to/random-article # - Response: 200 OK with ArticleDetailSchema structure # - Fields: created (datetime), title (string), author (string), content (string) ``` -------------------------------- ### Schema Object for Request/Response Documentation Source: https://github.com/royhzq/djagger/blob/main/docs/source/user_guide.md Djagger uses Pydantic's BaseModel (aliased as Schema) to document request parameters (headers, cookies, path, query), request bodies, and responses. Docstrings and Field attributes are used for descriptions and additional metadata. ```APIDOC ## Schema Object for Request/Response Documentation ### Description Djagger utilizes Pydantic's `BaseModel` (aliased as `Schema`) to define the structure and documentation for API requests and responses. This includes path parameters, query parameters, headers, cookies, request bodies, and responses. ### Key Features: - **Docstrings**: Extracted to describe the schema and its fields. - **Optional Fields**: Use `typing.Optional` or `typing.Union[..., None]` for fields that are not required. - **Field Customization**: `pydantic.Field` can be used to specify default values, descriptions, minimum/maximum values, and other constraints. ### Example Usage ```python from pydantic import BaseModel as Schema, Field from typing import Optional class MyResponse(Schema): """This docstring will be used to describe the response""" name : str age : int remarks : Optional[str] email : str = Field("default@example.com", description="This is a description of the field") ``` ### Further Reading Refer to [Pydantic's documentation](https://pydantic-docs.helpmanual.io/) for more details on schema definition and field customization. ``` -------------------------------- ### Djagger Attributes with Global Prefix Source: https://github.com/royhzq/djagger/blob/main/docs/source/user_guide.md Demonstrates how to use Djagger attributes after setting a global prefix. Both class-based and function-based views require the specified prefix (e.g., 'dj_') before Djagger attributes like summary, request_schema, and response_schema. ```python # Class-based view from rest_framework.views import APIView class TestView(APIView): dj_get_summary="Test View" dj_request_schema=... dj_response_schema=... # Function-based view from djagger.decorators import schema @schema( dj_get_summary="Test View" dj_request_schema=... dj_response_schema=... ) def fbv(request): ... ``` -------------------------------- ### Djagger Settings Configuration in settings.py Source: https://github.com/royhzq/djagger/blob/main/docs/source/user_guide.md This snippet shows the DJAGGER_DOCUMENT dictionary in Django's settings.py, which defines the OpenAPI schema's metadata, including version, title, description, license, app names, tags, tag groups, and server information. ```python DJAGGER_DOCUMENT = { "version" : "1.0.0", "title" : "Djagger Toy Store", "description" : """This is a sample OpenAPI 3.0 schema generated from a Django project using Djagger.\n\nView the Django project that generated this document on Github: https://github.com/royhzq/djagger-example.\n\n """, "license_name" : "MIT", "app_names" : [ 'Toy', 'Store', 'User', 'Blog'], "tags" : [ { 'name':'Toy', 'description': 'Toy App'}, { 'name':'Store', 'description': 'Store App'}, { 'name':'User', 'description': 'User App'}, { 'name':'Blog', 'description': 'Blog App'}, ], "x-tagGroups" : [ { 'name':'GENERAL', 'tags': ['Toy', 'Store', 'Blog']}, { 'name':'USER MANAGEMENT', 'tags': ['User']} ], "servers" : [ { "url":"https://example.org", "description":"Production API server" }, { "url":"https://staging.example.org", "description":"Staging API server" } ], } ``` -------------------------------- ### POST /articles/create Source: https://context7.com/royhzq/djagger/llms.txt Creates a new blog article by accepting a request schema for the article details and returning a response schema with the complete article information. ```APIDOC ## POST /articles/create ### Description Creates a new blog article. This endpoint validates the incoming request data against `ArticleCreateSchema` and returns the created article details using `ArticleDetailSchema`. ### Method POST ### Endpoint /articles/create ### Parameters #### Request Body - **title** (string) - Required - Title of Blog article, min_length=1, max_length=200 - **content** (string) - Required - Blog article content, min_length=10 ### Request Example ```json { "title": "My First Blog Post", "content": "This is the content of my first blog post." } ``` ### Response #### Success Response (201) - **id** (integer) - Unique identifier for the article. - **created** (datetime) - Timestamp when the article was created. - **title** (string) - Title of the blog article. - **author** (string) - Username of the article author. - **content** (string) - The full content of the blog article. #### Response Example ```json { "id": 123, "created": "2023-10-27T10:00:00Z", "title": "My First Blog Post", "author": "user123", "content": "This is the content of my first blog post." } ``` ``` -------------------------------- ### Group APIs with Tags in DRF View Source: https://github.com/royhzq/djagger/blob/main/docs/source/user_guide.md This example shows how to group API endpoints using the `tags` attribute in a Django REST Framework `APIView`. It illustrates how to assign tags to all operations of a view and how to use method-specific tags like `post_tags` for different HTTP methods. If `tags` are not explicitly set, Djagger uses the Django app name as the tag. ```python class MyView(APIView): tags = ['MyApp'] post_tags = ['Admin'] def get(self, request): # Assigned to 'MyApp' tag ... return Response({}) def post(self, request): # Assigned to 'Admin' tag ... return Response({}) ``` -------------------------------- ### POST /toys Source: https://context7.com/royhzq/djagger/llms.txt Add a new toy to the catalog. This endpoint accepts a ToySchema object and returns the created toy with an assigned ID. ```APIDOC ## POST /toys ### Description Create a new toy in the catalog. This endpoint accepts a `ToySchema` object and returns the created toy with an assigned ID. ### Method POST ### Endpoint /toys ### Parameters #### Request Body - **id** (integer) - Optional - Unique toy identifier - **name** (string) - Required - Toy name (min_length: 1, max_length: 100) - **category** (object) - Optional - Toy category information - **id** (integer) - Required - Category ID - **name** (string) - Required - Category name - **description** (string) - Optional - Category description - **photoUrls** (array) - Required - URLs of toy photos - **items** (string) - **tags** (array) - Optional - Associated tags - **items** (object) - **id** (integer) - Required - Tag ID - **name** (string) - Required - Tag name - **color** (string) - Required - Hex color code (pattern: `^#[0-9A-Fa-f]{6}$`) - **status** (string) - Optional - Toy status (enum: available, pending, sold) (default: available) - **price** (number) - Required - Price in USD (gt: 0) - **stock_quantity** (integer) - Required - Available stock (ge: 0) ### Request Example ```json { "name": "Robot Transformer Deluxe", "category": { "id": 1, "name": "Action Figures", "description": "Collectible action figures and toys" }, "photoUrls": [ "https://example.com/photos/robot1.jpg", "https://example.com/photos/robot2.jpg" ], "tags": [ { "id": 1, "name": "robots", "color": "#FF5733" }, { "id": 2, "name": "transformers", "color": "#33FF57" } ], "status": "available", "price": 49.99, "stock_quantity": 150 } ``` ### Response #### Success Response (201) - **id** (integer) - Unique toy identifier - **name** (string) - Toy name - **category** (object) - Toy category information - **id** (integer) - Category ID - **name** (string) - Category name - **description** (string) - Optional - Category description - **photoUrls** (array) - URLs of toy photos - **items** (string) - **tags** (array) - Associated tags - **items** (object) - **id** (integer) - Tag ID - **name** (string) - Tag name - **color** (string) - Hex color code - **status** (string) - Toy status - **price** (number) - Price in USD - **stock_quantity** (integer) - Available stock #### Response Example ```json { "id": 12345, "name": "Robot Transformer Deluxe", "category": { "id": 1, "name": "Action Figures", "description": "Collectible action figures and toys" }, "photoUrls": [ "https://example.com/photos/robot1.jpg", "https://example.com/photos/robot2.jpg" ], "tags": [ { "id": 1, "name": "robots", "color": "#FF5733" }, { "id": 2, "name": "transformers", "color": "#33FF57" } ], "status": "available", "price": 49.99, "stock_quantity": 150 } ``` ``` -------------------------------- ### Global Attribute Prefix Source: https://github.com/royhzq/djagger/blob/main/docs/source/user_guide.md Set a global prefix for Djagger attributes in your settings to prevent naming collisions with other packages. ```APIDOC ## Global Attribute Prefix ### Description When Djagger attributes conflict with attributes from other packages in your views, you can set a global prefix to resolve these conflicts. All Djagger attributes will then need to be prefixed accordingly. ### Configuration Add the `global_prefix` key to the `DJAGGER_CONFIG` dictionary in your `settings.py`. ```python DJAGGER_CONFIG = { "global_prefix": "dj_" } ``` ### Example with Prefix **Class-based view:** ```python from rest_framework.views import APIView class TestView(APIView): dj_get_summary = "Test View" # dj_request_schema = ... # dj_response_schema = ... ... ``` **Function-based view:** ```python from djagger.decorators import schema @schema( dj_get_summary="Test View" # dj_request_schema=... # dj_response_schema=... ) def fbv(request): ... ``` ``` -------------------------------- ### Generic Views Source: https://github.com/royhzq/djagger/blob/main/docs/source/user_guide.md Djagger automatically uses the `serializer_class` attribute of a generic view as its `response_schema`. This behavior can be overridden by explicitly defining `response_schema`. ```APIDOC ## Generic Views ### Description For generic views, Djagger treats a defined `serializer_class` attribute as the `response_schema`. This can be overridden by setting `response_schema` directly on the view. Documenting generic views follows similar principles to regular class-based views. ### Method GET, POST ### Endpoint `/blog/categories/` (Inferred from example) ### Parameters #### Query Parameters None specified in the example. #### Request Body For POST requests, the request body schema is not explicitly defined but would typically align with the `CategorySerializer` for creating a category. ### Request Example For POST requests: ```json { "example": "Category creation request body" } ``` ### Response #### Success Response (200) For GET requests, the response body will be a list conforming to `CategorySerializer` (as `many=True` is used). For POST requests, the response body will be the created category, conforming to `CategorySerializer`. #### Response Example For GET requests: ```json { "example": "List of categories response body" } ``` For POST requests: ```json { "example": "Single category response body" } ``` ``` -------------------------------- ### Document DRF Viewset Actions with Schema Decorator Source: https://github.com/royhzq/djagger/blob/main/docs/source/user_guide.md This snippet demonstrates how to document individual actions within a DRF Viewset using the `@schema` decorator. It shows how to specify HTTP methods, provide a summary, and link response schemas. Parent viewset attributes can also be used for documentation, with `@schema` decorators taking precedence. ```python class CategoryViewset(viewsets.ViewSet): """Example Viewset documentation""" response_schema = CategoryListSchema @schema( methods=['GET'], summary="List Categories", ) def list(self, request): ... return Response({}) @schema( methods=['GET'], summary="Get Category", response_schema=CategorySerializer, ) def retrieve(self, retrieve): ... return Response({}) ``` -------------------------------- ### Using Serializers Source: https://github.com/royhzq/djagger/blob/main/docs/source/user_guide.md Djagger allows the use of Django REST Framework Serializers as an alternative to Pydantic models for defining request and response schemas. ```APIDOC ## Using Serializers with Class-Based Views ### Description Djagger supports using Django REST Framework (DRF) serializers where Pydantic models are expected for schemas. Djagger internally converts DRF serializers into Pydantic models for documentation generation. ### Method PUT ### Endpoint `/blog/articles/update` (Inferred from example) ### Parameters #### Query Parameters None specified in the example. #### Request Body The request body should conform to `ArticleUpdateSerializer`. - **pk** (int) - Required - Primary key of the article to update. - **title** (str) - Optional - The new title for the article. - **content** (str) - Optional - The new content for the article. ### Request Example ```json { "pk": 123, "title": "Updated Article Title", "content": "Updated article content." } ``` ### Response #### Success Response (200) The response body will conform to `ArticleDetailSchema` (not fully defined in the provided text, but assumed to represent article details). #### Response Example ```json { "example": "Article detail response body" } ``` ```