📌  相关文章
📜  django ninja "schema" - Python (1)

📅  最后修改于: 2023-12-03 14:40:46.410000             🧑  作者: Mango

Django Ninja "schema" - Python

Django Ninja is a powerful web framework for building APIs with Django and Python 3.6+.

One of the key features of Django Ninja is its automatic schema generation. The schema is a JSON object that defines the available endpoints of your API and the data that each endpoint expects.

Schema Generation

Django Ninja automatically generates a schema based on your API views and serializers.

Generating the Schema

To generate the schema, you can use the get_schema() function provided by Django Ninja. Here is an example:

from django.urls import path
from ninja import Router, Schema

router = Router()

class ExampleSchema(Schema):
    name: str
    age: int

@router.get("/example/")
def example(request):
    """
    Example view
    """
    return {"Hello": "world!"}

# generate the schema
schema = router.get_schema()
Viewing the Schema

Once you have generated the schema, you can view it by visiting the /api/schema/ endpoint in your browser (assuming that /api/ is the base URL of your API).

The schema is returned in JSON format, so you can also view it using tools such as Postman or curl.

Here is an example of what the schema might look like:

{
    "openapi": "3.0.0",
    "info": {
        "title": "Example API",
        "version": "1.0.0"
    },
    "servers": [
        {"url": "http://localhost:8000/api/"}
    ],
    "paths": {
        "/example/": {
            "get": {
                "operationId": "example_read",
                "responses": {
                    "200": {
                        "description": "Success"
                    }
                },
                "tags": [
                    "example"
                ]
            }
        }
    },
    "components": {
        "schemas": {
            "ExampleSchema": {
                "type": "object",
                "properties": {
                    "name": {"type": "string"},
                    "age": {"type": "integer"}
                }
            }
        }
    }
}
Extending the Schema

You can extend the schema by adding additional components such as security definitions, parameters, and responses.

from ninja.security import APIKeyHeader

router = Router()

class ExampleSchema(Schema):
    name: str
    age: int

@router.get("/example/")
def example(request):
    """
    Example view
    """
    return {"Hello": "world!"}

# add security definitions to the schema
router.add_api_key_header(
    name="Authorization",
    scheme_name="API Key",
    header_name="X-API-Key"
)

# generate the schema with extended components
schema = router.get_schema(
    title="Example API",
    version="1.0.0",
    components={
        "securitySchemes": {
            "API Key": {
                "type": "apiKey",
                "in": "header",
                "name": "X-API-Key"
            }
        },
        "parameters": {
            "LimitQueryParam": {
                "in": "query",
                "name": "limit",
                "schema": {
                    "type": "integer",
                    "minimum": 1,
                    "maximum": 100
                },
                "description": "Limit the number of items returned in the response"
            }
        },
        "responses": {
            "ValidationError": {
                "description": "Validation Error",
                "content": {"application/json": {"example": {"detail": "Some validation error occurred"}}}
            },
            "PermissionDenied": {
                "description": "Permission Denied",
                "content": {"application/json": {"example": {"detail": "You do not have permission to perform this action."}}}
            }
        }
    }
)
Conclusion

Django Ninja's automatic schema generation is a powerful and flexible way to document your API endpoints and provide easy access to information about how your API works. By leveraging the power of Python's typing system, Django Ninja is able to generate a detailed schema with minimal code.