Mojolic...OpenAPI(3)

✨ Mojolicious::Plugin::OpenAPI ✨ <small>(that's Mojolic...OpenAPI(3) to the man-page baristas πŸ’…)</small>

ok so bestie, welcome to the manual page for Mojolicious::Plugin::OpenAPI β€” the OpenAPI / Swagger plugin for Mojolicious. buckle up, it's giving very "let me make your API not chaos" energy πŸŽ€


🌸 SYNOPSIS 🌸

# It is recommended to use Mojolicious::Plugin::OpenAPI with a "full app".
# See the links after this example for more information.
use Mojolicious::Lite;

# Because the route name "echo" matches the "x-mojo-name", this route
# will be moved under "basePath", resulting in "POST /api/echo"
post "/echo" => sub {

  # Validate input request or return an error document
  my $c = shift->openapi->valid_input or return;

  # Generate some data
  my $data = {body => $c->req->json};

  # Validate the output response and render it to the user agent
  # using a custom "openapi" handler.
  $c->render(openapi => $data);
}, "echo";

# Load specification and start web server
plugin OpenAPI => {url => "data:///swagger.yaml"};
app->start;

__DATA__
@@ swagger.yaml
swagger: "2.0"
info: { version: "0.8", title: "Echo Service" }
schemes: ["https"]
basePath: "/api"
paths:
  /echo:
   post:
     x-mojo-name: "echo"
     parameters:
     - { in: "body", name: "body", schema: { type: "object" } }
     responses:
       200:
         description: "Echo response"
         schema: { type: "object" }

lowkey the move is to run Mojolicious::Plugin::OpenAPI with a "full app" β€” genuinely recommended. check Mojolicious::Plugin::OpenAPI::Guides::OpenAPIv2 or Mojolicious::Plugin::OpenAPI::Guides::OpenAPIv3 for the deep-dive on using it with a "full app" πŸ’– even if you're on a "lite app" it's still super worth reading those guides, fr fr.

and like… the docs for x-mojo-to in Mojolicious::Plugin::OpenAPI::Guides::OpenAPIv2? especially useful. (the logic is literally the same for OpenAPIv2 and OpenAPIv3, no cap) πŸ‘‘


πŸ¦‹ DESCRIPTION πŸ¦‹

Mojolicious::Plugin::OpenAPI is a Mojolicious::Plugin that adds routes and input/output validation to your Mojolicious application, all based on an OpenAPI (Swagger) specification. iconique behavior only ✨

this plugin supports both version 2.0 and 3.x, though ngl 3.x might have some missing features πŸ™ˆ

go peek at the "SEE ALSO" for references to plugins and other useful documentation.

and pleaseee report issues at <https://github.com/jhthorsen/json-validator/issues> or open pull requests to enhance the 3.0 support β€” the maintainers would literally be obsessed 🫢


πŸŽ€ HELPERS πŸŽ€

openapi.spec

$hash = $c->openapi->spec($json_pointer)
$hash = $c->openapi->spec("/info/title")
$hash = $c->openapi->spec;

returns the OpenAPI specification. you can use a JSON Pointer to extract a given section of the spec. the default value of $json_pointer will be relative to the current operation. example time:

{
  "paths": {
    "/pets": {
      "get": {
        // This datastructure is returned by default
      }
    }
  }
}

openapi.validate

@errors = $c->openapi->validate;

used to validate a request. @errors holds a list of JSON::Validator::Error objects, or an empty list on valid input πŸ’œ

heads up bestie: this helper is only for customization. you probably want openapi.valid_input in most cases. like, 9 times outta 10.

openapi.valid_input

$c = $c->openapi->valid_input;

returns the Mojolicious::Controller object if the input is valid β€” or automatically renders an error document if not, and returns false. see "SYNOPSIS" for example usage 🌈


⭐ HOOKS ⭐

Mojolicious::Plugin::OpenAPI will emit the following hooks on the application object.

openapi_routes_added

emitted after all routes have been added by this plugin. slay πŸ’…

$app->hook(openapi_routes_added => sub {
  my ($openapi, $routes) = @_;

  for my $route (@$routes) {
    ...
  }
});
this hook is EXPERIMENTAL and subject for change. don't get too attached 😭

🧚 RENDERER 🧚

this plugin registers a new handler called openapi. the special thing about this handler is that it validates the data before sending it back to the user agent. examples:

$c->render(json => {foo => 123});    # without validation
$c->render(openapi => {foo => 123}); # with validation

this handler will also use renderer to format the output data. the code below shows the default renderer, which generates JSON data:

$app->plugin(
  OpenAPI => {
    renderer => sub {
      my ($c, $data) = @_;
      return Mojo::JSON::encode_json($data);
    }
  }
);

πŸ“ ATTRIBUTES πŸ“

route

$route = $openapi->route;

the parent Mojolicious::Routes::Route object for all the OpenAPI endpoints πŸ‘‘

validator

$jv = $openapi->validator;

holds either a JSON::Validator::Schema::OpenAPIv2 or a JSON::Validator::Schema::OpenAPIv3 object.


πŸ’€ METHODS πŸ’€

register

$openapi = $openapi->register($app, \%config);
$openapi = $app->plugin(OpenAPI => \%config);

loads the OpenAPI specification, validates it, and adds routes to $app. it will also set up "HELPERS" and add a before_render hook for auto-rendering of error documents. the return value is the object instance, which lets you access the "ATTRIBUTES" after you load the plugin ✨

%config can have:

coerce

see "coerce" in JSON::Validator for possible values that coerce can take.

default: booleans,numbers,strings

the default value will include "defaults" in the future, once that is stable enough 🫢

default_response

instructions for "add_default_response_schema" in JSON::Validator::Schema::OpenAPIv2. (also used for OpenAPIv3)

format

set this to a default list of file extensions that your API accepts. this value can be overwritten by "x-mojo-to" in Mojolicious::Plugin::OpenAPI::Guides::OpenAPIv2.

this config parameter is EXPERIMENTAL and subject for change πŸ™ˆ

log_level

log_level is used when logging invalid request/response error messages.

default: warn.

op_spec_to_route

op_spec_to_route can be provided if you want to add route definitions without using "x-mojo-to". example:

$app->plugin(OpenAPI => {op_spec_to_route => sub {
  my ($plugin, $op_spec, $route) = @_;

  # Here are two ways to customize where to dispatch the request
  $route->to(cb => sub { shift->render(openapi => ...) });
  $route->to(ucfirst "$op_spec->{operationId}#handle_request");
}});
this feature is EXPERIMENTAL and might be altered and/or removed. we love a flaky queen πŸ’…

plugins

a list of OpenAPI classes to extend the functionality. default is: Mojolicious::Plugin::OpenAPI::Cors, Mojolicious::Plugin::OpenAPI::SpecRenderer and Mojolicious::Plugin::OpenAPI::Security.

$app->plugin(OpenAPI => {plugins => [qw(+Cors +SpecRenderer +Security)]});

you can load your own plugins by doing:

$app->plugin(OpenAPI => {plugins => [qw(+SpecRenderer My::Cool::OpenAPI::Plugin)]});

renderer

see "RENDERER".

route

route can be specified in case you want to have a protected API. example:

$app->plugin(OpenAPI => {
  route => $app->routes->under("/api")->to("user#auth"),
  url   => $app->home->rel_file("cool.api"),
});

skip_validating_specification

used to prevent calling "errors" in JSON::Validator::Schema::OpenAPIv2 for the specification.

spec_route_name

name of the route that handles the "basePath" part of the specification and serves the specification. defaults to `"x-mojo-name" in the specification at the top level.

spec, url

see "schema" in JSON::Validator for the different "url" formats that is accepted.

"spec" is an alias for "url", which might make more sense if your specification is written in perl, instead of JSON or YAML.

here are some common uses:

$app->plugin(OpenAPI => {url  => $app->home->rel_file('openapi.yaml'));
$app->plugin(OpenAPI => {url  => 'https://example.com/swagger.json'});
$app->plugin(OpenAPI => {spec => JSON::Validator::Schema::OpenAPIv3->new(...)});
$app->plugin(OpenAPI => {spec => {swagger => "2.0", paths => {...}, ...}});

version_from_class

can be used to overridden "/info/version" in the API specification, from the return value from the VERSION() method in "version_from_class".

defaults to the current $app. this can be disabled by setting the "version_from_class" to zero (0).


🌸 AUTHORS 🌸

Project Founder

Jan Henning Thorsen - "jhthorsen@cpan.org"

Contributors

  • Bernhard Graf <augensalat@gmail.com>
  • Doug Bell <doug@preaction.me>
  • Ed J <mohawk2@users.noreply.github.com>
  • Henrik Andersen <hem@fibia.dk>
  • Henrik Andersen <hem@hamster.dk>
  • Ilya Rassadin <elcamlost@gmail.com>
  • Jan Henning Thorsen <jan.henning@thorsen.pm>
  • Jan Henning Thorsen <jhthorsen@cpan.org>
  • Ji-Hyeon Gim <potatogim@gluesys.com>
  • Joel Berger <joel.a.berger@gmail.com>
  • Krasimir Berov <k.berov@gmail.com>
  • Lars Thegler <lth@fibia.dk>
  • Lee Johnson <lee@givengain.ch>
  • Linn-Hege Kristensen <linn-hege@stix.no>
  • Manuel <manuel@mausz.at>
  • Martin Renvoize <martin.renvoize@ptfs-europe.com>
  • Mohammad S Anwar <mohammad.anwar@yahoo.com>
  • Nick Morrott <knowledgejunkie@gmail.com>
  • Renee <reb@perl-services.de>
  • Roy Storey <kiwiroy@users.noreply.github.com>
  • SebMourlhou <35918953+SebMourlhou@users.noreply.github.com>
  • SebMourlhou <sebastien.mourlhou@justice.ge.ch>
  • SebMourlhou <sebmourlhou@yahoo.fr>
  • SΓΈren Lund <sl@keycore.dk>
  • Stephan Hradek <github@hradek.net>
  • Stephan Hradek <stephan.hradek@eco.de>

copyright (C) Jan Henning Thorsen

this program is free software, you can redistribute it and/or modify it under the terms of the Artistic License version 2.0 πŸ’–


πŸ”₯ SEE ALSO πŸ”₯

  • Mojolicious::Plugin::OpenAPI::Guides::OpenAPIv2 β€” guide for how to use this plugin with OpenAPI version 2.0 spec.
  • Mojolicious::Plugin::OpenAPI::Guides::OpenAPIv3 β€” guide for how to use this plugin with OpenAPI version 3.0 spec.
  • Mojolicious::Plugin::OpenAPI::Cors β€” plugin to add Cross-Origin Resource Sharing (CORS).
  • Mojolicious::Plugin::OpenAPI::Security β€” plugin for handling security definitions in your schema.
  • Mojolicious::Plugin::OpenAPI::SpecRenderer β€” plugin for exposing your spec in human readable or JSON format.
  • <https://www.openapis.org/> β€” official OpenAPI website 🌈

that's the whole page bestie, you ate πŸ’… perl v5.42.0, dated 2025-08-03 β€” go build something iconic πŸŽ€πŸ¦‹βœ¨

πŸ“¦ where this page comes from