NAME
PAGI::FastAPI - Asynchronous, Type-Safe Micro-Framework with Dependency Injection and OpenAPI & Swagger UI
VERSION
Version v1.0.0
SYNOPSIS
use v5.38;
use PAGI::FastAPI;
use PAGI::FastAPI::Depends qw(Depends);
use Types::Standard qw(Int Str);
use Future::AsyncAwait;
my $app = PAGI::FastAPI->new(
title => 'Store Microservice',
version => '1.0.0',
);
# 1. Add CORS Support (delegates to PAGI::Middleware::CORS from PAGI::Tools)
$app->add_cors(
origins => ['https://example.com'],
methods => ['GET', 'POST'],
);
# 2. Add Authentication Middleware Hook
# (hand-rolled here for illustration only, for ready-made schemes,
# including proper 401 challenges, see PAGI::FastAPI::Security)
$app->add_middleware(async sub ($c, $next) {
my $auth = $c->header('Authorization') // '';
if ($auth ne 'Bearer secret_token') {
$c->status(401);
return { detail => 'Unauthorized' };
}
$c->stash->{user_id} = 42;
return await $next->($c);
});
# 3. Register Lifespan Handlers
$app->on_startup(async sub {
warn "Connecting to database connection pool...\n";
});
$app->on_shutdown(async sub {
warn "Closing database connections...\n";
});
# 4. Declare Async Dependencies
my $get_db = async sub ($c) {
return { db_name => 'production_db' };
};
my $get_current_user = async sub ($c) {
my $token = $c->header('Authorization') // '';
unless ($token eq 'Bearer secret_token') {
$c->status(401);
return { detail => 'Invalid credentials' };
}
return { user_id => 42, role => 'admin' };
};
# 5. Route using HashRef Dependency Map
$app->get('/profile',
dependencies => {
db => $get_db,
user => $get_current_user,
},
handler => async sub ($c) {
my $db = $c->stash->{db};
my $user = $c->stash->{user};
return { user => $user, db => $db->{db_name} };
}
);
# 6. Route using Depends() Array Spec
$app->get('/admin',
dependencies => [
Depends($get_current_user, key => 'user'),
async sub ($c) {
if ($c->stash->{user}{role} ne 'admin') {
$c->status(403);
return { detail => 'Admin privileges required' };
}
}
],
handler => async sub ($c) {
return { message => 'Welcome to admin panel' };
}
);
# 7. Non-blocking GET route with path parameter & query validation
$app->get('/items/{id}',
query => { limit => Int },
handler => async sub ($c) {
return {
item_id => $c->param('id'),
limit => $c->param('limit'),
status => 'active',
};
}
);
# 8. Non-blocking POST route with JSON payload validation
$app->post('/items',
body => { name => Str, price => Int },
handler => async sub ($c) {
return {
created => 1,
name => $c->body('name'),
price => $c->body('price'),
};
}
);
# 9. Non-blocking WebSocket Endpoint
# $ws is a PAGI::WebSocket (from PAGI::Tools), so on_close/each_json/
# try_send_json/keepalive and more are all built in.
$app->websocket('/ws', handler => async sub ($ws, $deps) {
await $ws->accept;
$ws->on_close(async sub {
my ($code, $reason) = @_;
# runs on every disconnect path, not just a clean loop exit
});
await $ws->each_json(async sub {
my ($data) = @_;
await $ws->send_json({ echo => $data });
});
});
# 10. Authentication via the companion PAGI::FastAPI::Security distribution
# (extraction only, you supply the verification logic)
#
# use PAGI::FastAPI::Security::HTTPBearer;
# my $bearer = PAGI::FastAPI::Security::HTTPBearer->new;
# $app->get('/secure',
# dependencies => [ $bearer->depends(key => 'token') ],
# handler => async sub ($c) {
# return { token => $c->stash->{token} };
# }
# );
#
# See L<PAGI::FastAPI::Security> for HTTP Basic, API Key
# (header/query/cookie), and OAuth2 password-bearer schemes.
my $pagi_app = $app->to_app;
DESCRIPTION
PAGI::FastAPI is an asynchronous micro-framework for modern Perl (5.36+) inspired by Python's FastAPI.
It combines non-blocking async execution via Future::AsyncAwait on the PAGI (Perl Asynchronous Gateway Interface) specification with request parameter validation via Type::Tiny and automatic interactive documentation generation.
Key Features
PAGI Protocol Engine: Asynchronous and non-blocking natively, built for scalable web applications.
Sub-App & Static Mounting: Mount external PAGI applications, file drivers, or sub-routers using mount().
WebSocket Support: Full non-blocking WebSocket handshake and frame streaming via PAGI::WebSocket.
CORS:
add_corsdelegates to PAGI::Middleware::CORS (from PAGI::Tools) rather than a separate implementation.Automatic Type Validation: Request query parameters and JSON payloads are checked against Type::Tiny constraints before reaching route handlers.
Automatic Interactive Docs: Serves an interactive Swagger UI interface at
/docsand machine-readable OpenAPI 3.1 JSON at/openapi.json.HTTP 422 Interception: Automatically intercepts invalid or missing parameters and returns formatted JSON errors with an
HTTP 422 Unprocessable Entitystatus code.Pluggable Authentication: Authentication is implemented as ordinary dependencies and middleware, with no framework lock-in. For ready-made schemes (HTTP Bearer, HTTP Basic, API Key, OAuth2 password bearer), see the companion distribution PAGI::FastAPI::Security, see "AUTHENTICATION AND SECURITY" below.
METHODS
new(%options)
my $app = PAGI::FastAPI->new(
title => 'My API',
version => '1.2.3',
);
Instantiates a new PAGI::FastAPI instance. Acceptable named arguments:
title- (Optional) Title string for the application and OpenAPI specification. Default:'PAGI::FastAPI Application'.version- (Optional) Version string for the OpenAPI specification. Default:'$VERSION'.secret- (Optional) Application-level secret scalar. Currently used as the defaultsecretfor "enable_csrf" when nosecretis passed to that call directly. Storing an app-wide secret here lets you avoid repeating it at every call site that needs it.
get($path, %options), post($path, %options), put($path, %options), patch($path, %options), delete($path, %options)
Registers a route for the specified HTTP verb. Options include:
query- (Optional) HashRef mapping query string keys to Type::Tiny type constraints.body- (Optional) HashRef mapping request body keys to Type::Tiny type constraints. The request body is parsed as JSON by default; if theContent-Typeheader isapplication/x-www-form-urlencoded, it is parsed as form-urlencoded data instead. Either way, the same type constraints and validation apply.dependencies- (Optional) HashRef or ArrayRef of dependency code blocks or PAGI::FastAPI::Depends specs.handler- (Required) Anasync sub ($c)code reference executing business logic. Receives a PAGI::FastAPI::Context instance.
mount($path_prefix, $pagi_app)
$app->mount('/css', PAGI::App::File->new(root => './public/css')->to_app);
$app->mount('/api/v2', $v2_sub_app);
Mounts a standalone PAGI application closure or sub-application under the given path prefix. Under the hood, to_app() composes mounted applications using PAGI::App::URLMap.
on_startup($code_ref), on_shutdown($code_ref), on_event($event_type, $code_ref)
Registers async callbacks for PAGI Lifespan Protocol events ('startup' or 'shutdown').
add_middleware
$app->add_middleware($middleware, %opts);
Appends a middleware component to the application's middleware execution stack.
The $middleware parameter can be passed as a class name or an instantiated object:
Class Name (String): Automatically loads the class via
require(dying on load failure) and instantiates it by calling$middleware->new(%opts).Object Instance: Attached directly. If the object implements PAGI wrapper interfaces (e.g.,
wrap,to_app, orcall), it is placed into the PAGI middleware stack; otherwise, it is routed to the legacy/internal middleware stack.
Returns $self to allow method chaining.
Example Usage:
# Pass class name with constructor options:
$app->add_middleware('PAGI::Middleware::Session', secret => 'my-secret');
# Pass an instantiated middleware object:
my $mw = PAGI::Middleware::Logger->new(level => 'debug');
$app->add_middleware($mw);
enable_csrf
$app->enable_csrf(%options);
Enables Cross-Site Request Forgery (CSRF) protection on the application by instantiating and attaching PAGI::Middleware::CSRF.
By default, the middleware is configured with enforce => 'header' and secure => 0. Any passed %options override these defaults.
secret(Scalar, optional)The cryptographic secret key used to sign and verify CSRF tokens. If omitted from
%options, it falls back to the application-levelsecretattribute set during PAGI::FastAPI instantiation. Dies if no secret can be resolved from either location.%options(Hash, optional)Additional configuration arguments passed directly to "new" in PAGI::Middleware::CSRF (such as
cookie_name,token_length, orsecure).
Returns $self to allow method chaining.
Example Usage:
# Uses application-level default secret:
my $app = PAGI::FastAPI->new(secret => 'master-app-secret');
$app->enable_csrf();
# Custom secret and production settings:
$app->enable_csrf(
secret => 'csrf-specific-secret',
secure => 1,
);
add_cors(%options)
Enables Cross-Origin Resource Sharing (CORS), including automatic handling of OPTIONS preflight requests, by delegating to PAGI::Middleware::CORS (from PAGI::Tools) rather than a hand-rolled implementation, see that module's own documentation for the authoritative behaviour. Options (matching PAGI::Middleware::CORS's own names exactly, so they mean the same thing here as anywhere else in the PAGI ecosystem):
origins- ArrayRef of allowed origins (default:['*']).methods- ArrayRef of allowed HTTP methods (default:['GET','POST','PUT','DELETE','PATCH','OPTIONS']).headers- ArrayRef of allowed request headers (default:['Content-Type','Authorization','X-Requested-With']).expose_headers- ArrayRef of headers to expose to the client (default:[]).credentials- Boolean enabling credentials support (default:0).max_age- Preflight cache max age in seconds (default:86400).
Changed in v0.1.0: previously this took allow_origins/allow_methods/ allow_headers/allow_credentials and implemented CORS handling directly in PAGI::FastAPI. It's now a thin wrapper that hands your options straight to PAGI::Middleware::CORS, so the option names above match that module's exactly.
websocket($path, %options)
$app->websocket('/ws/{room}',
handler => async sub ($ws, $deps) {
await $ws->accept;
while (defined(my $msg = await $ws->receive_text)) {
await $ws->send_text("Room $ws->path_params->{room}: $msg");
}
}
);
Registers a WebSocket endpoint at $path. The handler receives a PAGI::WebSocket instance and an optional HashRef of resolved dependencies.
add_rate_limit(%options)
$app->add_rate_limit(
requests => 100,
window => 60, # 100 requests per 60s
key_cb => sub ($c) { $c->header('X-API-Key') // '127.0.0.1' },
);
Registers application-wide rate limiting middleware.
add_bot_protection(%options)
$app->add_bot_protection(
difficulty => 3,
secret => $ENV{BOT_PROTECTION_SECRET},
ttl => 300,
);
Enables Proof-of-Work (PoW) bot protection middleware globally across the application.
When configured, incoming requests lacking valid x-bot-challenge and x-bot-nonce headers are intercepted and rejected with an HTTP 401 Unauthorized response containing a signed challenge token. Legitimate client browsers solve the cryptographic puzzle in JavaScript and retry the request automatically.
Accepts the following named options:
difficulty(Optional)Integer specifying the number of leading zeros required in the calculated SHA-256 hash collision. Higher values exponentially increase CPU effort for client devices while keeping server verification costs near-instant. Defaults to
3.secret(Optional)A secret seed scalar used to generate HMAC signatures for challenges. Must be customised in production environments to prevent challenge tampering or forgery. Defaults to
'change_me_in_production'.ttl(Optional)Integer specifying the validity duration of generated challenges in seconds. Defaults to
300(5 minutes).
Returns $self to support method chaining.
sse($generator, %options)
$app->get('/api/v1/llm-stream', sub ($c) {
return $c->sse(async sub ($sse) {
await $sse->keepalive(15);
for my $token ("Hello", " world!", " SSE!") {
await $sse->send_json({ token => $token });
await $c->sleep(0.1);
}
await $sse->close;
});
});
Returns a PAGI::FastAPI::Response::SSE response object for real-time Server-Sent Events (SSE) streaming.
Accepts an asynchronous code reference $generator receiving a PAGI::SSE instance, followed by optional named arguments:
headers(Optional)ArrayRef of additional HTTP headers to include in the handshake response (e.g.,
headers => [ ['X-Stream-ID' => '123'] ]).status(Optional)Integer status code for the initial HTTP handshake response. Defaults to
200.
Inside the generator callback, use $sse methods such as send_event(), send_json(), send(), keepalive(), and close().
Returns an instance of PAGI::FastAPI::Response::SSE.
to_pagi
my $pagi_app = $app->to_pagi();
Compiles the application into a single, executable PAGI-compliant async code reference ready to be served by an ASGI/PAGI application server (such as PAGI::Server) or wrapped by PAGI::Test::Client.
This method:
- 1. Builds the core route handling application via
$self->to_app(). - 2. Wraps the application in reverse order (LIFO - Last-In, First-Out) with all registered PAGI middleware components so that the first added middleware is executed first on incoming HTTP requests.
Middleware objects are wrapped based on their supported interface:
Objects with
wrap: Invokes$mw->wrap($app).Objects with
to_app: Invokes$mw->to_app($app).Code references: Invokes
$mw->($app).
Returns an async CODEREF matching the PAGI interface async sub ($scope, $receive, $send).
Example Usage:
my $app = PAGI::FastAPI->new();
$app->enable_csrf(secret => 'my-secret');
$app->get('/health', handler => async sub ($c) { { status => 'ok' } });
# Compile for server deployment or test runner
my $pagi_app = $app->to_pagi();
to_app()
my $pagi_closure = $app->to_app;
Generates and returns an asynchronous code reference conforming to the PAGI protocol specification. If sub-applications were registered via mount(), to_app() automatically wraps the routes using PAGI::App::URLMap.
AUTO-GENERATED ENDPOINTS
PAGI::FastAPI automatically registers the following system endpoints:
GET /docs- Serves an interactive Swagger UI web viewer in the browser.GET /openapi.json- Serves the generated OpenAPI 3.1 schema.
ERROR HANDLING
When a request fails parameter validation (either query string or JSON/form-urlencoded body), PAGI::FastAPI short-circuits handler execution and returns HTTP 422 Unprocessable Entity with a JSON body:
{
"detail": "Query param 'priority' invalid: Undef did not pass type constraint"
}
Unmatched routes return HTTP 404 Not Found with {"detail": "Not Found"}.
EVENT LOOPS: FUTURE::IO IS THE GOAL, IO::ASYNC IS AN IMPLEMENTATION DETAIL
The PAGI protocol is deliberately silent on which event loop drives it, that's meant to be an implementation detail of whichever server runs your app, not part of the application-level contract. PAGI::Server, the reference server, happens to use IO::Async today, but don't write your own application code as if that's guaranteed or load-bearing. Prefer Future::IO for anything loop-driven you write yourself (timers, delays, periodic tasks) and it keeps working regardless of which backend a given PAGI server chooses, now or in the future.
For a periodic task (a heartbeat or a cache sweep, anything you'd otherwise reach for a timer object for), prefer a self-rescheduling coroutine over constructing an IO::Async::Timer::Periodic (or any other loop-specific timer class) directly:
use Future::AsyncAwait;
use Future::IO;
async sub heartbeat {
while (1) {
await Future::IO->sleep(30);
...
}
}
heartbeat()->retain;
No loop object of your own to construct or own, Future::IO->sleep delegates to whatever backend is already configured in the process, whatever that turns out to be.
Why "prefer" and not "always," then? Pragmatically, the Future::IO ecosystem is still growing, and not every library has caught up to it yet. You'll sometimes still need a loop-specific integration for a particular dependency, most commonly Mojo::Pg or anything else built directly on Mojo::IOLoop, which predates Future::IO and doesn't use it. Treat the rest of this section as a workaround for that specific, narrower situation, not as a description of how PAGI::FastAPI itself works, which it doesn't depend on.
Fallback: bridging a Mojo::IOLoop-based dependency
If your handlers depend on a library on a different event loop from whatever the PAGI server ends up using, concretely, Mojo::Pg or anything else on Mojo::IOLoop, calling that library's non-blocking/callback API will do nothing: separate reactors by default don't service each other. The symptom is a request or on_startup/on_shutdown handler that just hangs (and, under PAGI::Server, eventually fails with a lifespan-timeout error) even though the call you're await-ing looks correct.
Conversely, calling that library in blocking mode instead (e.g. plain $pg->db->query(...) with no callback) does fire promptly, but freezes the entire process, every other in-flight request and WebSocket connection, for the duration of that call, since it's a real synchronous call with nothing cooperative about it. This is easy to end up with by accident: the blocking form is the default/simplest way to call most of these libraries, and it will work correctly in every manual test with one client before degrading badly under concurrent load.
The fix, when PAGI::Server happens to be running on IO::Async (which, again, is an implementation detail you shouldn't assume, but is true of the reference server today): get IO::Async and the other library's loop onto the same underlying reactor, so a single running loop drives both.
To make IO::Async work with the reactor, one must install the IO::Async::Loop::EV because it is the one used when one installs EV, which is done by Mojo::IOLoop automatically. Note that installing plain EV will not work: the constructor used for IO::Async::Loop will not automatically prefer
EVeven if it has been installed.Establish the
IO_ASYNC_LOOP=EVvariable for the entire process prior to starting the loop. This is necessary even when the IO::Async::Loop is created by someone else’s code, for instance,pagi-server.IO_ASYNC_LOOP=EV pagi-server your_app.plThroughout the whole task, utilise the callback/non-blocking variant of the API from another library (for example, the command
$pg->db->query($sql, @binds, $cb)), using aFutureto wrap up every call so that it can be executed usingawait-ed like any other command. Consult the information available in the Future::AsyncAwait regarding the routineFuture->new/$f->done/$f->failfor more information.
Without both (1) and (2), the two reactors remain separate no matter how correctly you use await on your side.
AUTHENTICATION AND SECURITY
PAGI::FastAPI has no authentication built in by design, auth needs vary too much between applications to standardise, so the framework gives you two general-purpose building blocks instead:
Middleware (
add_middleware), runs for every request, good for a single global auth check.Dependencies (the
dependenciesroute option, or PAGI::FastAPI::Depends), runs per-route, good for auth that varies by endpoint (e.g. some routes public, some requiring a token, some requiring a specific role).
A dependency signals an auth failure the same way any other dependency signals failure: by calling $c->status($code) with a code >= 400 and returning a body HashRef, which short-circuits the route handler before it runs:
my $get_current_user = async sub ($c) {
my $token = $c->header('Authorization') // '';
unless ($token eq 'Bearer secret_token') {
$c->status(401);
return { detail => 'Invalid credentials' };
}
return { user_id => 42, role => 'admin' };
};
Note that a dependency must signal failure this way, not by dieing, dependency execution is not wrapped in an eval, so a dying dependency propagates as an uncaught exception instead of a clean HTTP response.
Ready-made schemes: PAGI::FastAPI::Security
Writing the token-extraction and 401/403-response boilerplate above by hand for every scheme gets repetitive. The companion distribution PAGI::FastAPI::Security provides ready-made, Depends()-compatible classes for the common HTTP authentication schemes, modelled on Python FastAPI's fastapi.security module:
PAGI::FastAPI::Security::HTTPBearer -
Authorization: Bearer <token>, with a proper401+WWW-Authenticate: Bearerchallenge on failure.PAGI::FastAPI::Security::HTTPBasic -
Authorization: Basic <base64>, with a401+WWW-Authenticate: Basic realm="..."> challenge.PAGI::FastAPI::Security::APIKey - an API key read from a header, query string parameter, or cookie, with a
403on failure.PAGI::FastAPI::Security::OAuth2::PasswordBearer - OAuth2 bearer-token extraction plus
token_url/scopesmetadata for future OpenAPIsecuritySchemesgeneration.
Each scheme only extracts the credential, it deliberately does not verify it, so you aren't locked into one JWT library, password-hashing scheme, or identity provider. Pair it with your own verification as a second dependency:
use PAGI::FastAPI::Security::HTTPBearer;
use PAGI::FastAPI::Depends qw(Depends);
my $bearer = PAGI::FastAPI::Security::HTTPBearer->new;
$app->get('/items',
dependencies => [
$bearer->depends(key => 'token'),
Depends(async sub ($c) {
my $claims = eval { verify_jwt($c->stash->{token}) };
unless ($claims) {
$c->status(401);
return { detail => 'Invalid or expired token' };
}
return $claims;
}, key => 'claims'),
],
handler => async sub ($c) {
return { user_id => $c->stash->{claims}{sub} };
},
);
Every scheme also accepts auto_error => 0, resolving to undef instead of short-circuiting, for routes that behave differently for authenticated vs. anonymous requests. See PAGI::FastAPI::Security for the full documentation and an end-to-end JWT-verification example.
SEE ALSO
PAGI - Perl Asynchronous Gateway Interface specification.
PAGI::App::URLMap - Routing middleware for prefix-matching PAGI applications.
PAGI::WebSocket - Asynchronous WebSocket connection object (from PAGI::Tools) used by
websocket()handlers.PAGI::Middleware::CORS - CORS middleware (from PAGI::Tools) used by
add_cors.Future::IO - Loop-agnostic async I/O primitives; see "EVENT LOOPS: FUTURE::IO IS THE GOAL, IO::ASYNC IS AN IMPLEMENTATION DETAIL".
PAGI::FastAPI::Context - Context object passed to route handlers.
PAGI::FastAPI::Depends - Dependency injection helper.
PAGI::FastAPI::Security - Ready-made authentication schemes (HTTP Bearer, HTTP Basic, API Key, OAuth2 password bearer) for
dependencies.DBIx::Class::Async - Async DBIx::Class integration; see eg/dbic_async_integration.pl for a worked example with this framework.
Type::Tiny - Efficient Perl type constraint system.
Future::AsyncAwait - Async/Await syntax for Perl.
AUTHOR
Mohammad Sajid Anwar, <mohammad.anwar at yahoo.com>
REPOSITORY
https://github.com/manwar/PAGI-FastAPI
BUGS
Please report any bugs or feature requests through the web interface at https://github.com/manwar/PAGI-FastAPI/issues. I will be notified and then you'll automatically be notified of progress on your bug as I make changes.
SUPPORT
You can find documentation for this module with the perldoc command.
perldoc PAGI::FastAPI
You can also look for information at:
BUG Report
CPAN Ratings
Search MetaCPAN
LICENSE AND COPYRIGHT
Copyright (C) 2026 Mohammad Sajid Anwar.
This program is free software; you can redistribute it and/or modify it under the terms of the Artistic License (2.0).