Plack::Request(3)

✨ NAME ✨

okay bestie, welcome to Plack::Request(3) β€” the manual for Plack::Request, the portable HTTP request object from a PSGI env hash. That's the NAME line, folded in and cute. 🫢

🌸 SYNOPSIS 🌸

use Plack::Request;

my $app_or_middleware = sub {
    my $env = shift; # PSGI env

    my $req = Plack::Request->new($env);

    my $path_info = $req->path_info;
    my $query     = $req->parameters->{query};

    my $res = $req->new_response(200); # new Plack::Response
    $res->finalize;
};

πŸ’… DESCRIPTION πŸ’…

Plack::Request provides a consistent API for request objects across web server environments. ✨

😭 CAVEAT 😭

Note that this module is intended to be used by Plack middleware developers and web application framework developers rather than application developers (end users). πŸ’…

Writing your web application directly using Plack::Request is certainly possible but not recommended: it's like doing so with mod_perl's Apache::Request: yet too low level. 😭

If you're writing a web application, not a framework, then you're encouraged to use one of the web application frameworks that support PSGI (<http://plackperl.org/#frameworks>), or see modules like HTTP::Engine to provide higher level Request and Response API on top of PSGI.

If you're looking for an easy-to-use API to convert existing CGI applications to run on PSGI, consider using CGI::PSGI or CGI::Emulate::PSGI as well. CGI::Emulate::PSGI documentation has a good summary of using them to convert existing CGI scripts to adapt to PSGI. πŸ“

πŸ”₯ METHODS πŸ”₯

Some of the methods defined in the earlier versions are deprecated in version 0.99. Take a look at INCOMPATIBILITIES. πŸ‘€

Unless otherwise noted, all methods and attributes are read-only, and passing values to the method like an accessor doesn't work like you expect it to. So don't try it, bestie. πŸ™ˆ

✨ new ✨

Plack::Request->new( $env );

Creates a new request object. πŸŽ€

πŸ‘‘ ATTRIBUTES πŸ‘‘

  • env β€” Returns the shared PSGI environment hash reference. This is a reference, so writing to this environment passes through during the whole PSGI request/response cycle. πŸ”₯
  • address β€” Returns the IP address of the client (REMOTE_ADDR).
  • remote_host β€” Returns the remote host (REMOTE_HOST) of the client. It may be empty, in which case you have to get the IP address using the address method and resolve on your own. 😭
  • method β€” Contains the request method (GET, POST, HEAD, etc).
  • protocol β€” Returns the protocol (HTTP/1.0 or HTTP/1.1) used for the current request.
  • request_uri β€” Returns the raw, undecoded request URI path. You probably do NOT want to use this to dispatch requests. πŸ’€
  • path_info β€” Returns PATH_INFO in the environment. Use this to get the local path for the requests.
  • path β€” Similar to path_info but returns / in case it is empty. In other words, it returns the virtual path of the request URI after $req->base. See DISPATCHING for details.
  • query_string β€” Returns QUERY_STRING in the environment. This is the undecoded query string in the request URI.
  • script_name β€” Returns SCRIPT_NAME in the environment. This is the absolute path where your application is hosted.
  • scheme β€” Returns the scheme (http or https) of the request.
  • secure β€” Returns true or false, indicating whether the connection is secure (https).
  • body, input β€” Returns psgi.input handle.
  • session β€” Returns (optional) psgix.session hash. When it exists, you can retrieve and store per-session data from and to this hash.
  • session_options β€” Returns (optional) psgix.session.options hash.
  • logger β€” Returns (optional) psgix.logger code reference. When it exists, your application is supposed to send the log message to this logger, using:
$req->logger->({ level => 'debug', message => "This is a debug message" });
  • cookies β€” Returns a reference to a hash containing the cookies. Values are strings that are sent by clients and are URI decoded. If there are multiple cookies with the same name in the request, this method will ignore the duplicates and return only the first value. If that causes issues for you, you may have to use modules like CGI::Simple::Cookie to parse $request->header('Cookie') by yourself. πŸͺ
  • query_parameters β€” Returns a reference to a hash containing query string (GET) parameters. This hash reference is a Hash::MultiValue object.
  • body_parameters β€” Returns a reference to a hash containing posted parameters in the request body (POST). As with query_parameters, the hash reference is a Hash::MultiValue object.
  • parameters β€” Returns a Hash::MultiValue hash reference containing (merged) GET and POST parameters.
  • content, raw_body β€” Returns the request content in an undecoded byte string for POST requests.
  • uri β€” Returns an URI object for the current request. The URI is constructed using various environment values such as SCRIPT_NAME, PATH_INFO, QUERY_STRING, HTTP_HOST, SERVER_NAME and SERVER_PORT. Every time this method is called it returns a new, cloned URI object. ✨
  • base β€” Returns an URI object for the base path of current request. This is like uri but only contains up to SCRIPT_NAME where your application is hosted at. Every time this method is called it returns a new, cloned URI object.
  • user β€” Returns REMOTE_USER if it's set.
  • headers β€” Returns an HTTP::Headers::Fast object containing the headers for the current request.
  • uploads β€” Returns a reference to a hash containing uploads. The hash reference is a Hash::MultiValue object and values are Plack::Request::Upload objects.
  • content_encoding β€” Shortcut to $req->headers->content_encoding.
  • content_length β€” Returns the raw value of the Content-Length header. Before version 0.9925, this method was a shortcut for $req->headers->content_length.
  • content_type β€” Returns the raw value of the Content-Type header. If you want just the MIME type, without any attributes like charset, use $req->headers->content_type. See also "content_type" in HTTP::Headers. Before version 0.9925, this method was a shortcut for $req->headers->content_type.
  • header β€” Shortcut to $req->headers->header.
  • referer β€” Shortcut to $req->headers->referer.
  • user_agent β€” Shortcut to $req->headers->user_agent.
  • param β€” Returns GET and POST parameters with a CGI.pm-compatible param method. This is an alternative method for accessing parameters in $req->parameters just in case you want the compatibility with CGI.pm objects. You are not recommended to use this method since it is easy to misuse in a list context such as inside a hash constructor or method arguments. Use parameters and Hash::MultiValue instead. Unlike CGI.pm, it does not allow setting or modifying query parameters.
$value  = $req->param( 'foo' );
@values = $req->param( 'foo' );
@params = $req->param;
  • upload β€” A convenient method to access $req->uploads.
$upload  = $req->upload('field');
@uploads = $req->upload('field');
@fields  = $req->upload;

for my $upload ( $req->upload('field') ) {
    print $upload->filename;
}
  • new_response β€” Creates a new Plack::Response object. Handy to remove dependency on Plack::Response in your code for easy subclassing and duck typing in web application frameworks, as well as overriding Response generation in middlewares.
my $res = $req->new_response;

πŸ’– Hash::MultiValue parameters πŸ’–

Parameters that can take one or multiple values (i.e. parameters, query_parameters, body_parameters and uploads) store the hash reference as a Hash::MultiValue object. This means you can use the hash reference as a plain hash where values are always scalars (NOT array references), so you don't need to code ugly and unsafe ref ... eq 'ARRAY' anymore. πŸ’…

And if you explicitly want to get multiple values of the same key, you can call the get_all method on it, such as:

my @foo = $req->query_parameters->get_all('foo');

You can also call get_one to always get one parameter independent of the context (unlike param), and even call mixed (with Hash::MultiValue 0.05 or later) to get the traditional hash reference,

my $params = $req->parameters->mixed;

where values are either a scalar or an array reference depending on input, so it might be useful if you already have the code to deal with that ugliness. 😭

🌈 PARSING POST BODY and MULTIPLE OBJECTS 🌈

The methods to parse request body (content, body_parameters and uploads) are carefully coded to save the parsed body in the environment hash as well as in the temporary buffer, so you can call them multiple times and create Plack::Request objects multiple times in a request and they should work safely, and won't parse request body more than twice for the efficiency. πŸ”₯

πŸš€ DISPATCHING πŸš€

If your application or framework wants to dispatch (or route) actions based on request paths, be sure to use $req->path_info not $req->uri->path. πŸ’…

This is because path_info gives you the virtual path of the request, regardless of how your application is mounted. If your application is hosted with mod_perl or CGI scripts, or even multiplexed with tools like Plack::App::URLMap, request's path_info always gives you the action path. ✨

Note that path_info might give you an empty string, in which case you should assume that the path is /. πŸ‘€

You will also want to use $req->base as a base prefix when building URLs in your templates or in redirections. It's a good idea for you to subclass Plack::Request and define methods such as:

sub uri_for {
    my($self, $path, $args) = @_;
    my $uri = $self->base;
    $uri->path($uri->path . $path);
    $uri->query_form(@$args) if $args;
    $uri;
}

So you can say:

my $link = $req->uri_for('/logout', [ signoff => 1 ]);

and if $req->base is /app you'll get the full URI for /app/logout?signoff=1. πŸŽ€

πŸ’€ INCOMPATIBILITIES πŸ’€

okay bestie, gather round, because this is the glow-up lore and some of y'all are gonna be personally attacked by it 😭

In version 0.99, a whole bunch of utility methods got removed or deprecated, and most methods got made read-only. And then those methods were straight up deleted in version 1.0001. gone gone. not coming back. πŸ’…

All the parameter-related methods β€” you know the ones, parameters, body_parameters, query_parameters and uploads β€” now contain Hash::MultiValue objects, instead of being a scalar or an array reference depending on what the user typed in. which was, and I cannot stress this enough, insecure. so yeah, glow-up for security. peep Hash::MultiValue if you wanna know more about this change 🫢

The $req->path method had a bug, where the code and the document were just... not matching at all. classic. The document was out here suggesting it returns the sub request path after $req->base, but the code was always returning the absolute URI path the whole time. scheming fr. The code is now updated to be an alias of $req->path_info, except it returns / in case it's empty. and if you need the older behavior? just call $req->uri->path instead. easy ✨

Cookie handling got simplified, and it doesn't use CGI::Simple::Cookie anymore, which means you CAN NOT set an array reference or a hash reference as a cookie value and expect it to be serialized. nope. You're always required to set a string value, and the encoding or decoding of them is totally up to your application or framework. do it yourself, bestie, I believe in you πŸŽ€

Also, the cookies hash reference now returns strings for the cookies rather than CGI::Simple::Cookie objects, which means you no longer have to write wacky code like this:

$v = $req->cookies->{foo} ? $req->cookies->{foo}->value : undef;

and instead, simply do:

$v = $req->cookies->{foo};

the way that just... cleaned up an entire line of chaos. iconic. we ate and left no crumbs πŸ‘‘


πŸ‘‘ AUTHORS πŸ‘‘

The absolute legends who built this:

  • Tatsuhiko Miyagawa
  • Kazuhiro Osawa
  • Tokuhiro Matsuno

main character energy from all three, no notes πŸ’œ


πŸ¦‹ SEE ALSO πŸ¦‹

Go read these next, bestie, they're the friend group:

  • Plack::Response
  • HTTP::Request
  • Catalyst::Request

🌸 LICENSE 🌸

This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. so go forth, share the love, it's giving open source royalty πŸ’–


aaaand that's the whole page, we made it 🫢 this was perl v5.42.3, all the way back on 2026-10-18, and you just finished reading Plack::Request(3). go build something cute with it. mwah. πŸ’…βœ¨

πŸ“¦ where this page comes from