import dyne
from dyne.ext.auth import authenticate, BasicAuth
from dyne.ext.io.pydantic import input, output, expect
from dyne.ext.openapi import OpenAPI
app = dyne.App()
db = Alchemical(app)
api = OpenAPI(app)
basic_auth = BasicAuth()
@api.route("/book", methods=["POST"])
@authenticate(basic_auth, role="admin")
@input(BookCreateSchema, location="form")
@output(BookSchema, status_code=201)
@expect({401: "Unauthorized", 400: "Invalid file format"})
async def create_book(req, resp, *, data):
"""
Create a new Book
---
This endpoint allows admins to upload a book cover and metadata.
"""
image = data.pop("image")
await image.asave(f"uploads/{image.filename}") # image is already validated for extension, size and filename.
session = await req.db
book = await Book.create(**data, cover=image.filename)
await session.commit()
resp.obj = bookDyne is a modern async framework for APIs and applications, featuring built-in authentication, validation & serialization (Pydantic & Marshmallow), automatic OpenAPI, GraphQL support (Strawberry & Graphene), and async SQLAlchemy integration via Alchemical all with minimal first class configuration.
It delivers a production-ready ASGI foundation out of the box. It features an integrated static file server powered by (WhiteNoise <http://whitenoise.evans.io/en/stable/>_), Jinja2 templating for dynamic rendering, and a high-performance uvloop-based webserver—all optimized with automatic Gzip compression for reduced latency.
See the documentation, for more details on features available in dyne.
Dyne uses optional dependencies (extras) to keep the core package lightweight.
This allows you to install only the features you need for your specific project.
To install the minimal ASGI core:
pip install dyneTo install all available features:
pip install "dyne[full]"Choose the bundle that fits your technology stack. Note that for most shells (like Zsh on macOS), you should wrap the package name in quotes to handle the brackets correctly.
Note: The use of brackets
[]is required.
Enable automated OpenAPI (Swagger) documentation, request validation and response serialization using your preferred schema library:
pip install "dyne[openapi_pydantic]"pip install "dyne[openapi_marshmallow]"Integrate a native GraphQL interface and the GraphiQL IDE:
pip install "dyne[graphql_strawberry]"pip install "dyne[graphql_graphene]"Database SQLAlchemy support with Alchemical
pip install "dyne[sqlalchemy]"To install all available features, including:
- Both GraphQL engines
- SQLAlchemy (Alchemical)
- Both serialization engines
- OpenAPI support
pip install "dyne[full]"The primary concept here is to bring the niceties that are brought forth from both Flask and Falcon and unify them into a single framework, along with some new ideas I have. I also wanted to take some of the API primitives that are instilled in the Requests library and put them into a web framework. So, you'll find a lot of parallels here with Requests.
- Setting
resp.contentsends back bytes. - Setting
resp.textsends back unicode, while settingresp.htmlsends back HTML. - Setting
resp.mediasends back JSON/YAML (.text/.html/.contentoverride this). - Setting
resp.objdeserializes SQLAlchemy object(s) using Pydantic or Marshmallow schemas - Case-insensitive
req.headersdict (from Requests directly). resp.status_code,req.method,req.url, and other familiar friends.
-
A built in testing client that uses the actual Requests you know and love.
-
A Pleasant Application Experience: Designed for developer happiness with a clean, intuitive, and consistent API.
-
Native ASGI Foundation: Built on the
ASGI <https://asgi.readthedocs.io>_ standard for high-performance, fully asynchronous applications. -
Expressive Routing: Declare routes using familiar
f-string syntax <https://docs.python.org/3/whatsnew/3.6.html#pep-498-formatted-string-literals>_, improving readability and maintainability. -
First-Class Configuration: Strongly typed, auto-casted configuration with
.envauto-discovery, environment variable overrides, and validation at startup. -
Database Integration: First-class
SQLAlchemysupport powered byAlchemical, providing clean session management, async-friendly patterns, and declarative configuration. -
Seamless API Documentation: Fully self-generated
OpenAPIdocumentation with an interactive UI and native support for bothPydanticandMarshmallowschemas. -
Flexible View Layer: Support for function-based or class-based views (without mandatory inheritance) and a mutable response object that simplifies response handling.
-
GraphQL Support: Native integration with
StrawberryandGraphene, includingGraphiQLfor interactive schema exploration. -
Webhooks & Async Events: First-class webhook definition and documentation via the
@webhookdecorator, enabling clearly defined outbound callbacks and event-driven workflows. -
Request & Response Lifecycle: Powerful decorators such as
@inputfor validation,@outputfor serialization, and@expectfor enforcing headers, cookies, and request metadata. -
Bidirectional Communication: Built-in support for
WebSocketsalongside traditional HTTP and GraphQL endpoints. -
Background Tasks: Easily offload long-running or blocking work using a built-in
ThreadPoolExecutor. -
Extensible Architecture: Mount any ASGI-compatible application at a subroute and serve single-page applications (SPAs) natively.
-
Integrated Security: First-class authentication support for
BasicAuth,TokenAuth, andDigestAuth. -
Advanced File Uploads: Robust file handling via a configurable
FileField, enabling seamless binary data validation and storage integration for bothPydanticandMarshmallowschemas.
