NAME
PAGI::FastAPI - Asynchronous, Type-Safe Micro-Framework with Dependency Injection and OpenAPI & Swagger UI
VERSION
Version v0.0.1
SYNOPSIS
use v5.36;
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
$app->add_cors(
allow_origins => ['https://example.com'],
allow_methods => ['GET', 'POST'],
);
# 2. Add Authentication Middleware Hook
$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'),
};
}
);
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.
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.
METHODS
new(%options)
my $app = PAGI::FastAPI->new(
title => 'My API',
version => '1.2.3',
);
Instantiates a new PAGI::FastAPI instance. Acceptable options:
title- (Optional) Title string for the application and OpenAPI specification. Default:'PAGI::FastAPI Application'.version- (Optional) Version string for the OpenAPI specification. Default:'$VERSION'.
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 JSON request body keys to Type::Tiny type constraints.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.
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($code_ref)
Registers an asynchronous middleware with the application. Signature:
$app->add_middleware(async sub ($c, $next) {
# Pre-processing...
my $res = await $next->($c);
# Post-processing...
return $res;
});
add_cors(%options)
Enables Cross-Origin Resource Sharing (CORS) with automatic handling of OPTIONS preflight requests. Options include:
allow_origins- ArrayRef or string of allowed origins (default:['*']).allow_methods- ArrayRef or string of allowed HTTP methods (default:['*']).allow_headers- ArrayRef or string of allowed HTTP headers (default:['*']).allow_credentials- Boolean enabling credentials support (default:0).max_age- Preflight cache max age in seconds (default:600).
to_app()
my $pagi_closure = $app->to_app;
Generates and returns an asynchronous code reference conforming to the PAGI protocol specification: sub ($scope, $receive, $send). This closure can be served directly via pagi-server.
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 payload), 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"}.
SEE ALSO
PAGI - Perl Asynchronous Gateway Interface specification.
PAGI::FastAPI::Context - Context object passed to route handlers.
PAGI::FastAPI::Depends - Dependency injection helper.
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). You may obtain a copy of the full license at:
http://www.perlfoundation.org/artistic_license_2_0
Any use, modification, and distribution of the Standard or Modified Versions is governed by this Artistic License. By using, modifying or distributing the Package, you accept this license. Do not use, modify, or distribute the Package, if you do not accept this license.
If your Modified Version has been derived from a Modified Version made by someone other than you, you are nevertheless required to ensure that your Modified Version complies with the requirements of this license.
This license does not grant you the right to use any trademark, service mark, tradename, or logo of the Copyright Holder.
This license includes the non-exclusive, worldwide, free-of-charge patent license to make, have made, use, offer to sell, sell, import and otherwise transfer the Package with respect to any patent claims licensable by the Copyright Holder that are necessarily infringed by the Package. If you institute patent litigation (including a cross-claim or counterclaim) against any party alleging that the Package constitutes direct or contributory patent infringement, then this Artistic License to you shall terminate on the date that such litigation is filed.
Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.