FastAPI/Context.pm

filter: Statementstmt 95.8% 116 / 121 Branchbran 84.3% 27 / 32 Conditioncond 69.2% 27 / 39 MC/DCmcdc 52.3% 11 / 21 Subroutinesub 93.7% 30 / 32 Podpod 100% 24 / 24 totaltotal 87.3% 235 / 269 CC 38 SCAR 14.9
CC
38
Cov
89%
csrf_token
12.6
file
6.0
background
5.1
CRAP 4.5
« FastAPI/Cookies.pm ↑ Summary FastAPI/Middleware/ExceptionHandler.pm »
1 package PAGI::FastAPI::Context;
2  
3 23 ▶use v5.38;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 23 ▶use experimental 'class';
Subroutine BEGIN: called CC=1 SCAR=0.0
5 23 ▶use version;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 23 our $VERSION = qv('v1.7.3');
8 23 our $AUTHORITY = 'cpan:MANWAR';
9  
10 23 class PAGI::FastAPI::Context {
11 23 ▶ use Future::IO;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 23 ▶ use Scalar::Util ();
Subroutine BEGIN: called CC=1 SCAR=0.0
13 23 ▶ use PAGI::FastAPI::Response::File qw(file_response);
Subroutine BEGIN: called CC=1 SCAR=0.0
14  
15 23 field $scope :param = {};
16 23 field $query_params :param = {};
17 23 field $path_params :param = {};
18 23 field $body :param = undef;
19 23 field $form_data :param = undef;
20 23 field $uploaded_files :param = {};
21 23 field $status :param = 200;
22 23 field $res_headers :param = [];
23 23 field $stash :param = {};
24 23 field $pagi_context :param = undef;
25 23 field $background_registrar :param = undef;
26  
27 1 ▶ method scope { $scope }
Subroutine scope: called CC=1 SCAR=0.0
Pod documented
28  
29 1 ▶ method sleep ($seconds) {
Subroutine sleep: called CC=1 SCAR=0.0
Pod documented
30 1 return Future::IO->sleep($seconds);
31 23 }
32  
33 95 ▶ method status ($val = undef) {
Subroutine status: called CC=3 SCAR=11.0
Pod documented
34 95 ▶ if (defined $val) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $val) 21 74 95
35 21 $status = $val;
36 }
37 95 return $status;
38 23 }
39  
40 0 ▶ method pagi_context { $pagi_context }
Subroutine pagi_context: not called CC=1 SCAR=1.2
Pod documented
41  
42 8 ▶ method csrf_token () {
Subroutine csrf_token: called CC=11 SCAR=25.3
Pod documented
43 # 1. Direct scope environment
44 8 ▶ if (defined $scope
Branch: 1 branch
BranchTrueFalseTotal
if (defined $scope and ref $scope eq "HASH" and $scope->{"pagi.csrf_token"}) 1 7 8
Condition50%3/6
defined $scope and ref $scope eq "HASH" and $scope->{"pagi.csrf_token"}
!ll&&!rl&&r
071
defined $scope and ref $scope eq "HASH"
!ll&&!rl&&r
008
MC/DC33%1/3
defined $scope and ref $scope eq "HASH" and $scope->{"pagi.csrf_token"}
defined $scope ref $scope eq "HASH" $scope->{"pagi.csrf_token"}
Truth table50%2/4
A and B and C
A= defined $scopeB= ref $scope eq "HASH"C= $scope->{"pagi.csrf_token"}
ABCresult
0XX0
10X0
1100
1111
45 && ref $scope eq 'HASH'
46 && $scope->{'pagi.csrf_token'}) {
47 1 return $scope->{'pagi.csrf_token'};
48 }
49  
50 # 2. PAGI context environment
51 7 ▶ if (defined $pagi_context
Branch: 1 branch
BranchTrueFalseTotal
if (defined $pagi_context and $pagi_context->can("env")) 1 6 7
Condition100%3/3
defined $pagi_context and $pagi_context->can("env")
!ll&&!rl&&r
241
MC/DC100%2/2
defined $pagi_context and $pagi_context->can("env")
defined $pagi_context $pagi_context->can("env")
Truth table100%3/3
A and B
A= defined $pagi_contextB= $pagi_context->can("env")
ABresult
0X0
100
111
52 && $pagi_context->can('env')) {
53 1 my $env = $pagi_context->env;
54 return $env->{'pagi.csrf_token'}
55 1 ▶ if $env && $env->{'pagi.csrf_token'};
Branch: 1 branch
BranchTrueFalseTotal
if $env and $env->{"pagi.csrf_token"} 1 0 1
Condition33%1/3
$env and $env->{"pagi.csrf_token"}
!ll&&!rl&&r
001
MC/DC0%0/2
$env and $env->{"pagi.csrf_token"}
$env $env->{"pagi.csrf_token"}
Truth table33%1/3
A and B
A= $envB= $env->{"pagi.csrf_token"}
ABresult
0X0
100
111
56 }
57  
58 # 3. Session storage fallback
59 6 ▶ if (defined $scope
Branch: 1 branch
BranchTrueFalseTotal
if (defined $scope and $scope->{"pagi.session"} and ref $scope->{"pagi.session"} eq "HASH") 5 1 6
Condition66%4/6
defined $scope and $scope->{"pagi.session"} and ref $scope->{"pagi.session"} eq "HASH"
!ll&&!rl&&r
105
defined $scope and $scope->{"pagi.session"}
!ll&&!rl&&r
015
MC/DC33%1/3
defined $scope and $scope->{"pagi.session"} and ref $scope->{"pagi.session"} eq "HASH"
defined $scope $scope->{"pagi.session"} ref $scope->{"pagi.session"} eq "HASH"
Truth table50%2/4
A and B and C
A= defined $scopeB= $scope->{"pagi.session"}C= ref $scope->{"pagi.session"} eq "HASH"
ABCresult
0XX0
10X0
1100
1111
60 && $scope->{'pagi.session'}
61 && ref $scope->{'pagi.session'} eq 'HASH') {
62 5 return $scope->{'pagi.session'}{'csrf_token'};
63 }
64  
65 1 return undef;
66 23 }
67  
68 2 ▶ method csrf_verify ($token) {
Subroutine csrf_verify: called CC=2 SCAR=6.9
Pod documented
69 2 ▶ die "PAGI context is not set" unless defined $pagi_context;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $pagi_context 1 1 2
70 1 return $pagi_context->csrf_verify($token);
71 23 }
72  
73 126 ▶ method res_headers { $res_headers }
Subroutine res_headers: called CC=1 SCAR=0.0
Pod documented
74  
75 16 ▶ method set_header ($key, $val) {
Subroutine set_header: called CC=3 SCAR=11.0
Pod documented
76 16 my $lc_key = lc($key);
77 16 for my $h (@$res_headers) {
78 28 ▶ if (lc($h->[0]) eq $lc_key) {
Branch: 1 branch
BranchTrueFalseTotal
if (lc $h->[0] eq $lc_key) 2 26 28
79 2 $h->[0] = $key;
80 2 $h->[1] = $val;
81 2 return;
82 }
83 }
84 14 push @$res_headers, [$key, $val];
85 23 }
86  
87 77 ▶ method add_header ($key, $val) {
Subroutine add_header: called CC=1 SCAR=0.0
Pod documented
88 77 push @$res_headers, [$key, $val];
89 23 }
90  
91 35 ▶ method header ($name) {
Subroutine header: called CC=4 SCAR=13.9
Pod documented
92 35 ▶ my $headers = $scope->{headers} // [];
Condition50%1/2
$scope->{"headers"} // []
l!l
350
MC/DC0%0/1
$scope->{"headers"} // []
$scope->{"headers"}
Truth table50%1/2
A
A= $scope->{"headers"}
Aresult
11
00
93 35 my $lc_name = lc($name);
94 35 for my $h (@$headers) {
95 38 ▶ return $h->[1] if lc($h->[0]) eq $lc_name;
Branch: 1 branch
BranchTrueFalseTotal
if lc $h->[0] eq $lc_name 32 6 38
96 }
97 3 return undef;
98 23 }
99  
100 0 ▶ method file ($filepath, %opts) {
Subroutine file: not called CC=2 SCAR=17.9
Pod documented
101 # For static assets served directly (like CSS/JS),
102 # set as_attachment => 0 by default unless explicitly overridden.
103 0 ▶ $opts{as_attachment} //= 0;
Condition0%0/2
$opts{"as_attachment"} //= 0
l!l
00
MC/DC0%0/1
$opts{"as_attachment"} //= 0
$opts{"as_attachment"}
Truth table0%0/2
A
A= $opts{"as_attachment"}
Aresult
11
00
104  
105 0 return file_response($filepath, %opts);
106 23 }
107  
108 6 ▶ method html ($content, %opts) {
Subroutine html: called CC=3 SCAR=11.0
Pod documented
109 23 ▶ use PAGI::FastAPI::Response::HTML;
Subroutine BEGIN: called CC=1 SCAR=0.0
110  
111 return PAGI::FastAPI::Response::HTML->new(
112 body => $content,
113 headers => $opts{headers} // [],
114 6 ▶ status => $opts{status} // 200,
Condition100%4/4
$opts{"headers"} // []
l!l
15
$opts{"status"} // 200
l!l
15
MC/DC100%1/1
$opts{"headers"} // []
$opts{"headers"}
MC/DC100%1/1
$opts{"status"} // 200
$opts{"status"}
Truth table100%2/2
A
A= $opts{"headers"}
Aresult
11
00
Truth table100%2/2
A
A= $opts{"status"}
Aresult
11
00
115 );
116 23 }
117  
118 1 ▶ method sse ($code) {
Subroutine sse: called CC=1 SCAR=0.0
Pod documented
119 23 ▶ use PAGI::FastAPI::Response::SSE;
Subroutine BEGIN: called CC=1 SCAR=0.0
120  
121 1 return PAGI::FastAPI::Response::SSE->new(
122 generator => $code,
123 );
124 23 }
125  
126 60 ▶ method path_params { $path_params }
Subroutine path_params: called CC=1 SCAR=0.0
Pod documented
127 59 ▶ method query_params { $query_params }
Subroutine query_params: called CC=1 SCAR=0.0
Pod documented
128  
129 12 ▶ method path_param ($name) {
Subroutine path_param: called CC=1 SCAR=0.0
Pod documented
130 12 return $path_params->{$name};
131 23 }
132  
133 8 ▶ method query_param ($name) {
Subroutine query_param: called CC=1 SCAR=0.0
Pod documented
134 8 return $query_params->{$name};
135 23 }
136  
137 42 ▶ method body ($key = undef) {
Subroutine body: called CC=4 SCAR=13.9
Pod documented
138 42 ▶ if (defined $key) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $key) 30 12 42
139 30 ▶ return (ref $body eq 'HASH') ? $body->{$key} : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $body eq 'HASH' ? : 30 0 30
140 }
141 12 return $body;
142 23 }
143  
144 4 ▶ method form_data ($key = undef) {
Subroutine form_data: called CC=4 SCAR=14.5
Pod documented
145 4 ▶ if (defined $key) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $key) 4 0 4
146 4 ▶ return (ref $form_data eq 'HASH') ? $form_data->{$key} : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $form_data eq 'HASH' ? : 3 1 4
147 }
148 0 return $form_data;
149 23 }
150  
151 1 ▶ method uploaded_files ($name = undef) {
Subroutine uploaded_files: called CC=4 SCAR=15.8
Pod documented
152 1 ▶ if (defined $name) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $name) 1 0 1
153 1 ▶ return $uploaded_files->{$name} // [];
Condition50%1/2
$uploaded_files->{$name} // []
l!l
10
MC/DC0%0/1
$uploaded_files->{$name} // []
$uploaded_files->{$name}
Truth table50%1/2
A
A= $uploaded_files->{$name}
Aresult
11
00
154 }
155 0 return $uploaded_files;
156 23 }
157  
158 4 ▶ method uploaded_file ($name) {
Subroutine uploaded_file: called CC=2 SCAR=6.9
Pod documented
159 4 ▶ my $files = $uploaded_files->{$name} // [];
Condition100%2/2
$uploaded_files->{$name} // []
l!l
13
MC/DC100%1/1
$uploaded_files->{$name} // []
$uploaded_files->{$name}
Truth table100%2/2
A
A= $uploaded_files->{$name}
Aresult
11
00
160 4 return $files->[0];
161 23 }
162  
163 5 ▶ method background ($code) {
Subroutine background: called CC=5 SCAR=16.3
Pod documented
164 5 ▶ die "background() expects a CODE reference (e.g. an async sub)\n"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $code eq "CODE" 1 4 5
165 unless ref $code eq 'CODE';
166  
167 4 my $future = $code->();
168  
169 4 ▶ die "background() callback did not return a Future, did you "
Branch: 1 branch
BranchTrueFalseTotal
unless builtin::blessed($future) and $future->isa("Future") 1 3 4
Condition66%2/3
builtin::blessed($future) and $future->isa("Future")
!ll&&!rl&&r
103
MC/DC50%1/2
builtin::blessed($future) and $future->isa("Future")
builtin::blessed($future) $future->isa("Future")
Truth table66%2/3
A and B
A= builtin::blessed($future)B= $future->isa("Future")
ABresult
0X0
100
111
170 . "forget 'async' before 'sub'?\n"
171 unless Scalar::Util::blessed($future) && $future->isa('Future');
172  
173 3 ▶ return $background_registrar ? $background_registrar->($future) : $future;
Branch: 1 branch
BranchTrueFalseTotal
$background_registrar ? : 3 0 3
174 23 }
175  
176 6 ▶ method param ($key) {
Subroutine param: called CC=3 SCAR=11.0
Pod documented
177 6 ▶ return $self->path_param($key)
Condition100%6/6
($self->path_param($key) // $self->query_param($key)) // $self->body($key)
l!l&&r!l&&!r
411
$self->path_param($key) // $self->query_param($key)
l!l&&r!l&&!r
222
MC/DC100%3/3
($self->path_param($key) // $self->query_param($key)) // $self->body($key)
$self->path_param($key) $self->query_param($key) $self->body($key)
Truth table100%4/4
A // B // C
A= $self->path_param($key)B= $self->query_param($key)C= $self->body($key)
ABCresult
1XX1
01X1
0011
0000
178 // $self->query_param($key)
179 // $self->body($key);
180 23 }
181  
182 18 ▶ method stash { $stash }
Subroutine stash: called CC=1 SCAR=0.0
Pod documented
183 }
184  
185 =encoding utf-8
186  
187 =head1 NAME
188  
189 PAGI::FastAPI::Context - Request and Response Lifecycle Context for PAGI::FastAPI
190  
191 =head1 VERSION
192  
193 Version v1.7.3
194  
195 =head1 SYNOPSIS
196  
197 # Inspecting Request Parameters
198 my $user_id = $c->path_param('id');
199 my $limit = $c->query_param('limit');
200 my $name = $c->body('name');
201  
202 # Generic Parameter Fallback (Path -> Query -> Body)
203 my $token = $c->param('token');
204  
205 # Headers & Scope
206 my $ua = $c->header('User-Agent');
207 my $scope = $c->scope;
208  
209 # Stash Storage
210 $c->stash->{user} = { id => 42, role => 'admin' };
211  
212 # Modifying Response State
213 $c->status(201);
214 $c->set_header('X-Custom-Header' => 'value');
215  
216 =head1 DESCRIPTION
217  
218 C<PAGI::FastAPI::Context> encapsulates the request environment, parsed parameters,
219 payload data, and response state for an individual HTTP exchange processed
220 by L<PAGI::FastAPI>.
221  
222 An instance of this context is passed as the primary argument to route handlers,
223 middleware functions, and dependency blocks.
224  
225 =head1 METHODS
226  
227 =head2 C<new(%args)>
228  
229 Constructor called internally by L<PAGI::FastAPI>. Accepts named arguments:
230  
231 =over 4
232  
233 =item * C<scope> - PAGI environment HashRef.
234  
235 =item * C<query_params> - HashRef of validated query parameters.
236  
237 =item * C<path_params> - HashRef of route path variables.
238  
239 =item * C<body> - Decoded payload body (HashRef, ArrayRef, or Scalar).
240  
241 =item * C<form_data> - HashRef of parsed form fields, for a request whose
242 body was C<application/x-www-form-urlencoded> or C<multipart/form-data>.
243 C<undef> for a JSON body.
244  
245 =item * C<uploaded_files> - HashRef of uploaded file parts from a
246 C<multipart/form-data> body, keyed by field name.
247  
248 =item * C<status> - Initial HTTP response code (default: C<200>).
249  
250 =item * C<res_headers> - Initial response headers ArrayRef (default: C<[]>).
251  
252 =item * C<stash> - Context-bound storage HashRef (default: C<{}>).
253  
254 =back
255  
256 =head2 C<scope()>
257  
258 Returns the raw PAGI scope HashRef for the current request.
259  
260 =head2 C<sleep($seconds)>
261  
262 await $c->sleep(1);
263  
264 Asynchronously pauses execution for the given number of seconds without blocking the event loop.
265  
266 Uses L<Future::IO> under the hood to ensure non-blocking sleep operations.
267  
268 =over 4
269  
270 =item * C<$seconds>
271  
272 Number of seconds to sleep (fractional seconds like C<0.5> are supported).
273  
274 =back
275  
276 Returns a L<Future> that completes when the specified sleep duration has elapsed.
277  
278 =head2 C<status([ $code ])>
279  
280 Gets or sets the HTTP status code for the response.
281  
282 $c->status(403);
283 my $code = $c->status; # 403
284  
285 =head2 C<pagi_context>
286  
287 my $pagi_ctx = $c->pagi_context;
288  
289 Returns the underlying low-level L<PAGI::Context> instance associated with
290 the current HTTP request. Useful for low-level protocol inspection, raw
291 environment access, or invoking protocol-specific extension methods.
292  
293 =head2 C<csrf_token>
294  
295 my $token = $c->csrf_token;
296  
297 Retrieves the active Anti-CSRF token for the current request.
298  
299 This method transparently attempts to resolve the token from three potential
300 locations in order of precedence:
301  
302 =over 4
303  
304 =item 1. B<Direct Scope Environment:> C<< $scope->{'pagi.csrf_token'} >> (set directly by L<PAGI::Middleware::CSRF>).
305  
306 =item 2. B<PAGI Context Environment:> C<< $pagi_context->env->{'pagi.csrf_token'} >>.
307  
308 =item 3. B<Session Storage Fallback:> C<< $scope->{'pagi.session'}{'csrf_token'} >> (set by session management middleware).
309  
310 =back
311  
312 Returns the scalar token string if found, or C<undef> if no token is
313 available or if CSRF/Session middleware is not active for the request.
314  
315 B<Example Usage (Embedding in HTML forms):>
316  
317 $app->get('/form', handler => async sub ($c) {
318 my $token = $c->csrf_token // '';
319 return $c->html(qq{
320 <form method="POST" action="/submit">
321 <input type="hidden" name="csrf_token" value="$token">
322 <button type="submit">Submit</button>
323 </form>
324 });
325 });
326  
327 =head2 C<csrf_verify($token)>
328  
329 my $is_valid = $c->csrf_verify($submitted_token);
330  
331 Explicitly validates the given C<$token> against the current request's CSRF
332 state by delegating to the underlying low-level L<PAGI::Context> instance.
333  
334 Accepts a scalar token string C<$token>. Returns a true value if the token
335 signature and expiration are valid; returns false otherwise.
336  
337 Dies with C<"PAGI context is not set"> if invoked when no low-level
338 L<PAGI::Context> instance is associated with C<$c>.
339  
340 B<Example Usage (Manual Verification):>
341  
342 $app->post('/api/action', handler => async sub ($c) {
343 my $token = $c->body('csrf_token');
344  
345 unless ($c->csrf_verify($token)) {
346 $c->status(403);
347 return { error => 'Invalid or missing CSRF token' };
348 }
349  
350 return { status => 'success' };
351 });
352  
353 =head2 C<res_headers()>
354  
355 Returns the current list of outgoing response header pairs as an ArrayRef of
356 tuple pairs C<[ [$name, $val], ... ]>.
357  
358 =head2 C<set_header($key, $val)>
359  
360 Sets an outgoing HTTP header, case-insensitively replacing any existing
361 header of the same name (last write wins). Use this for headers that
362 should only ever have one value.
363  
364 $c->set_header('X-Frame-Options' => 'DENY');
365 $c->set_header('Content-Type' => 'text/plain'); # replaces any prior Content-Type
366  
367 =head2 C<add_header($key, $val)>
368  
369 Appends an additional outgoing HTTP header pair without touching any
370 existing header of the same name. Use this only for headers that are
371 legitimately allowed to appear more than once (e.g. C<Set-Cookie>,
372 C<Vary>, C<Link>); for everything else prefer C<set_header>.
373  
374 $c->add_header('Set-Cookie' => 'session=abc123; Path=/');
375 $c->add_header('Set-Cookie' => 'theme=dark; Path=/');
376  
377 =head2 C<header($name)>
378  
379 Case-insensitively searches incoming request headers (from C<< $c->scope->{headers} >>)
380 and returns its scalar value, or C<undef> if missing.
381  
382 my $auth = $c->header('Authorization');
383  
384 =head2 C<file($filepath, %options)>
385  
386 $app->get('/assets/app.js', handler => async sub ($c) {
387 return $c->file('/var/www/static/app.js');
388 });
389  
390 $app->get('/reports/annual.pdf', handler => async sub ($c) {
391 return $c->file(
392 '/var/www/reports/2026.pdf',
393 as_attachment => 1,
394 filename => 'annual-report-2026.pdf',
395 );
396 });
397  
398 Constructs and returns a L<PAGI::FastAPI::Response::File> instance to stream a
399 file from disk to the client.
400  
401 Delegates directly to L<PAGI::FastAPI::Response::File/file_response>, with a
402 context-aware default of C<as_attachment =E<gt> 0> to ensure assets (such as CSS,
403 JavaScript, or images) display inline in the browser rather than triggering a
404 download prompt.
405  
406 Accepts the following named options:
407  
408 =over 4
409  
410 =item * C<as_attachment> (Boolean, optional)
411  
412 Controls the C<Content-Disposition> response header. Defaults to C<0> (inline)
413 when called via C<< $c->file >>. Set to C<1> to force the browser to download
414 the file as an attachment.
415  
416 =item * C<content_type> (String, optional)
417  
418 Explicitly overrides the MIME type sent in the C<Content-Type> header. When
419 omitted, the content type is guessed automatically from the file extension of
420 C<$filepath>.
421  
422 =item * C<filename> (String, optional)
423  
424 Sets a custom filename string for the C<Content-Disposition> header. Useful when
425 serving files stored under internal hashes or non-descriptive paths on disk.
426  
427 =item * C<status> (Integer, optional)
428  
429 The HTTP status code to return with the file response. Defaults to C<200>.
430  
431 =back
432  
433 Returns an instance of L<PAGI::FastAPI::Response::File>.
434  
435 =head2 C<html($content, %options)>
436  
437 $app->get('/about', handler => async sub ($c) {
438 return $c->html('<h1>About Us</h1>');
439 });
440  
441 Returns an HTTP response with the C<Content-Type> header automatically set to C<text/html; charset=utf-8>.
442  
443 Accepts the HTML content string as the first parameter, followed by optional named parameters:
444  
445 =over 4
446  
447 =item * C<status> (Optional)
448  
449 Integer HTTP status code. Defaults to C<200>.
450  
451 =item * C<headers> (Optional)
452  
453 ArrayRef of additional header key-value pairs.
454  
455 =back
456  
457 Returns a C<PAGI::FastAPI::Response> object.
458  
459 =head2 C<sse($code)>
460  
461 $app->get('/api/v1/metrics', handler => async sub ($c) {
462 return $c->sse(async sub ($stream) {
463 while (1) {
464 await $stream->send_json({ cpu => 42 });
465 await $c->sleep(1);
466 }
467 });
468 });
469  
470 Creates and returns a Server-Sent Events (SSE) response object.
471  
472 Accepts an async generator coderef that receives an SSE stream handler as
473 its first argument.
474  
475 =over 4
476  
477 =item * C<$code>
478  
479 An C<async sub> coderef that defines the event streaming loop. The callback
480 receives an instance of L<PAGI::SSE>, offering methods such as
481 C<send_event()>, C<send_json()>, C<send()>, C<keepalive()>, and C<close()>.
482  
483 =back
484  
485 Returns an instance of L<PAGI::FastAPI::Response::SSE>.
486  
487 =head2 C<path_params()>
488  
489 Returns the HashRef containing all parsed path parameters.
490  
491 =head2 C<path_param($key)>
492  
493 Returns a specific parsed path parameter by name, or C<undef> if absent.
494  
495 =head2 C<query_params()>
496  
497 Returns the HashRef containing all parsed query parameters.
498  
499 =head2 C<query_param($key)>
500  
501 Returns a specific parsed query parameter by name, or C<undef> if absent.
502  
503 =head2 C<body([ $key ])>
504  
505 If called without parameters, returns the full raw/decoded request body.
506  
507 If called with a C<$key> parameter and the body is a HashRef, returns the
508 value for that key, or C<undef> if missing or if the body is not a HashRef.
509  
510 my $full_body = $c->body;
511 my $user_name = $c->body('username');
512  
513 =head2 C<form_data([ $key ])>
514  
515 $app->post('/upload', handler => async sub ($c) {
516 my $caption = $c->form_data('caption');
517 ...
518 });
519  
520 Returns the parsed form fields for a request body that was either
521 C<application/x-www-form-urlencoded> or C<multipart/form-data>, with the
522 same calling convention as C<body>: no arguments returns the full HashRef,
523 a C<$key> argument returns that one field's value (or C<undef>).
524  
525 For a C<multipart/form-data> body, this returns only the plain text
526 fields, file parts are available separately via C<uploaded_files>.
527 C<undef> for a JSON body (JSON is not a form).
528  
529 Note that for both C<application/x-www-form-urlencoded> and
530 C<multipart/form-data> bodies, C<body> and C<form_data> return the I<same>
531 HashRef, C<form_data> exists as a clearer-named alias for form-sourced
532 data specifically, not as a separate parse.
533  
534 =head2 C<uploaded_files([ $field_name ])>
535  
536 my $all_files = $c->uploaded_files; # HashRef, keyed by field name
537 my $avatar_list = $c->uploaded_files('avatar'); # ArrayRef for one field
538  
539 Returns uploaded file parts from a C<multipart/form-data> request body.
540  
541 With no arguments, returns a HashRef keyed by field name. With a
542 C<$field_name> argument, returns just that field's files (or an empty
543 ArrayRef if none were uploaded under that name).
544  
545 Each file is always represented as an ArrayRef of HashRefs, even when only
546 one file was uploaded for that field, so a single-file C<< <input
547 type="file"> >> and a multi-file C<< <input type="file" multiple> >> have
548 the same shape to consume. Each file HashRef has:
549  
550 =over 4
551  
552 =item * C<filename> - The original filename supplied by the client.
553  
554 =item * C<content_type> - The C<Content-Type> declared for that part, or
555 C<application/octet-stream> if none was given.
556  
557 =item * C<content> - The raw file bytes.
558  
559 =item * C<size> - Byte length of C<content>.
560  
561 =back
562  
563 B<Note:> file contents are currently held fully in memory for the
564 duration of the request; there is no streaming or on-disk spooling for
565 large uploads.
566  
567 =head2 C<uploaded_file($field_name)>
568  
569 my $avatar = $c->uploaded_file('avatar');
570 if ($avatar) {
571 say "Got $avatar->{filename}, $avatar->{size} bytes";
572 }
573  
574 Convenience accessor for the common single-file-per-field case. Returns
575 the I<first> uploaded file HashRef for C<$field_name> (see
576 C<uploaded_files> above for its shape), or C<undef> if no file was
577 uploaded under that name.
578  
579 =head2 C<param($key)>
580  
581 Convenience parameter accessor that checks parameter stores in priority order:
582  
583 1. Path parameters (C<path_param>)
584 2. Query parameters (C<query_param>)
585 3. JSON/Body fields (C<body($key)>)
586  
587 Returns the first matching non-undef value, or C<undef> if the key is not
588 present in any store.
589  
590 =head2 C<stash()>
591  
592 Returns a HashRef tied to the lifecycle of this context. Useful for sharing
593 data between middleware, dependency injection blocks, and final route
594 handlers.
595  
596 $c->stash->{db_session} = $db;
597  
598 =head2 C<background($code)>
599  
600 $app->post('/signup', handler => async sub ($c) {
601 my $email = $c->body('email');
602  
603 $c->background(async sub {
604 await send_welcome_email($email); # runs after the response is sent
605 });
606  
607 return { status => 'account created' };
608 });
609  
610 Schedules an C<async sub> to keep running I<after> the response has
611 already been sent, without making the caller wait for it, for
612 fire-and-forget work like sending an email, writing an audit log entry, or
613 warming a cache.
614  
615 C<$code> must be an C<async sub> (or any coderef that, when called with no
616 arguments, returns a L<Future>); C<background> calls it immediately and
617 retains the resulting Future for you, so it won't be garbage-collected or
618 silently dropped before it completes, the same way the framework already
619 owns the request/response lifecycle. A task that dies is logged (via
620 C<warn>) rather than crashing the request that scheduled it, or any other
621 in-flight request.
622  
623 Retention is owned by the application, not the request: scheduled tasks
624 outlive the C<$c> that scheduled them, and any still-pending tasks are
625 awaited during PAGI Lifespan C<shutdown> (before your own C<on_shutdown>
626 callbacks run), so a task doesn't get killed mid-flight by process exit
627 under normal shutdown.
628  
629 Dies immediately, before scheduling anything, if C<$code> isn't a coderef,
630 or if calling it didn't return a L<Future> (the most common cause of the
631 latter: forgetting the C<async> keyword).
632  
633 =head1 AUTHOR
634  
635 Mohammad Sajid Anwar, C<< <mohammad.anwar at yahoo.com> >>
636  
637 =head1 REPOSITORY
638  
639 L<https://github.com/manwar/PAGI-FastAPI>
640  
641 =head1 BUGS
642  
643 Please report any bugs or feature requests through the web interface at L<https://github.com/manwar/PAGI-FastAPI/issues>.
644 I will be notified and then you'll automatically be notified of progress on your
645 bug as I make changes.
646  
647 =head1 SUPPORT
648  
649 You can find documentation for this module with the perldoc command.
650  
651 perldoc PAGI::FastAPI::Context
652  
653 You can also look for information at:
654  
655 =over 4
656  
657 =item * BUG Report
658  
659 L<https://github.com/manwar/PAGI-FastAPI/issues>
660  
661 =item * Search MetaCPAN
662  
663 L<https://metacpan.org/dist/PAGI-FastAPI/>
664  
665 =back
666  
667 =head1 LICENSE AND COPYRIGHT
668  
669 Copyright (C) 2026 Mohammad Sajid Anwar.
670  
671 This program is free software; you can redistribute it and/or modify it under
672 the terms of the Artistic License (2.0).
673  
674 =cut
675  
676 23 1; # End of PAGI::FastAPI::Context
« FastAPI/Cookies.pm ↑ Summary FastAPI/Middleware/ExceptionHandler.pm »