File: OpenAPIv2.pod

package info (click to toggle)
libmojolicious-plugin-openapi-perl 5.11-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 840 kB
  • sloc: perl: 1,324; makefile: 4
file content (285 lines) | stat: -rw-r--r-- 8,498 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
=head1 NAME

Mojolicious::Plugin::OpenAPI::Guides::OpenAPIv2 - Mojolicious <3 OpenAPI v2 (Swagger)

=head1 OVERVIEW

This guide will give you an introduction to how to use
L<Mojolicious::Plugin::OpenAPI> with OpenAPI version v2.

=head1 TUTORIAL

=head2 Specification

This plugin reads an L<OpenAPI specification|https://openapis.org/specification>
and generate routes and input/output rules from it. See L<JSON::Validator> for
L<supported schema file formats|JSON::Validator/Supported schema formats>.

  {
    "swagger": "2.0",
    "info": { "version": "1.0", "title": "Some awesome API" },
    "basePath": "/api",
    "paths": {
      "/pets": {
        "get": {
          "operationId": "getPets",
          "x-mojo-name": "get_pets",
          "x-mojo-to": "pet#list",
          "summary": "Finds pets in the system",
          "parameters": [
            {"in": "body", "name": "body", "schema": {"type": "object"}},
            {"in": "query", "name": "age", "type": "integer"}
          ],
          "responses": {
            "200": {
              "description": "Pet response",
              "schema": {
                "type": "object",
                "properties": {
                  "pets": {
                    "type": "array",
                    "items": { "type": "object" }
                  }
                }
              }
            }
          }
        }
      }
    }
  }

The complete HTTP request for getting the "pet list" will be C<GET /api/pets>
The first part of the path ("/api") comes from C<basePath>, the second part
comes from the keys under C<paths>, and the HTTP method comes from the keys
under C</pets>.

The different parts of the specification can also be retrieved as JSON using
the "OPTIONS" HTTP method. Example:

  OPTIONS /api/pets
  OPTIONS /api/pets?method=get

Note that the use of "OPTIONS" is EXPERIMENTAL, and subject to change.

Here are some more details about the different keys:

=over 2

=item * swagger and info

These two sections are required to make the specification valid. Check out
L<https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md>
for a complete reference to the specification.

=item * host, schemes, consumes, produces, security and securityDefinitions

These keys are currently not in use. "host" will be replaced by the "Host"
header in the request. The rest of the keys are currently not in use.

Submit an L<issue|https://github.com/jhthorsen/mojolicious-plugin-openapi/issues>
if you have ideas on what to use these keys for.

=item * basePath

The C<basePath> will also be used to add a route that renders back the
specification either as JSON or HTML. Examples:

=over 2

=item * http://example.com/api.html

Retrieve the expanded version of the API in human readable format. The
formatting is currently a bit rough, but should be easier than reading the JSON
spec.

=item * http://example.com/api.json

Retrieve the expanded version of the API, useful for JavaScript clients and
other client side applications.

=back

=item * parameters and responses

C<parameters> and C<responses> will be used to define input and output
validtion rules, which is used by L<Mojolicious::Plugin::OpenAPI/openapi.input>
and when rendering the response back to the client, using C<< render(openapi => ...) >>.

Have a look at L<Mojolicious::Plugin::OpenAPI/RENDERER> for more details about
output rendering.

=item * operationId and x-mojo-name

See L</Route names>.

=item * x-mojo-placeholder

C<x-mojo-placeholder> can be used inside a parameter definition to instruct
Mojolicious to parse a path part in a certain way. Example:

  "parameters": [
    {
      "x-mojo-placeholder": "#",
      "in": "path",
      "name": "email",
      "type": "string"
    }
  ]

See L<Mojolicious::Guides::Routing> for more information about "standard",
"relaxed" and "wildcard" placeholders. The default is to use the "standard"
("/:foo") placeholder.

=item * x-mojo-to

The non-standard part in the spec above is "x-mojo-to". The "x-mojo-to" key
can be either a plain string, object (hash) or an array. The string and hash
will be passed directly to L<Mojolicious::Routes::Route/to>, while the array
ref will be flatten. Examples:

  "x-mojo-to": "pet#list"
  $route->to("pet#list");

  "x-mojo-to": {"controller": "pet", "action": "list", "foo": 123}
  $route->to({controller => "pet", action => "list", foo => 123);

  "x-mojo-to": ["pet#list", {"foo": 123}, ["format": ["json"]]]
  $route->to("pet#list", {foo => 123});
  $route->pattern->constraints->{format} = ["json"];

=back

=head2 Application

  package Myapp;
  use Mojo::Base "Mojolicious";

  sub startup {
    my $app = shift;
    $app->plugin("OpenAPI" => {url => $app->home->rel_file("myapi.json")});
  }

  1;

The first thing in your code that you need to do is to load this plugin and the
L</Specification>. See L<Mojolicious::Plugin::OpenAPI/register> for information
about what the plugin config can be.

See also L<Mojolicious::Plugin::OpenAPI/SYNOPSIS> for example
L<Mojolicious::Lite> application.

=head2 Controller

  package Myapp::Controller::Pet;
  use Mojo::Base "Mojolicious::Controller";

  sub list {

    # Do not continue on invalid input and render a default 400
    # error document.
    my $c = shift->openapi->valid_input or return;

    # You might want to introspect the specification for the current route
    my $spec = $c->openapi->spec;
    unless ($spec->{'x-opening-hour'} == (localtime)[2]) {
      return $c->render(openapi => [], status => 498);
    }

    my $age  = $c->param("age");
    my $body = $c->req->json;

    # $output will be validated by the OpenAPI spec before rendered
    my $output = {pets => [{name => "kit-e-cat"}]};
    $c->render(openapi => $output);
  }

  1;

The input will be validated using
L<Mojolicious::Plugin::OpenAPI/openapi.valid_input> while the output is
validated through then L<openapi|Mojolicious::Plugin::OpenAPI/RENDERER>
handler.

=head2 Route names

Routes will get its name from either L</x-mojo-name> or from L</operationId> if
defined in the specification.

The route name can also be used the other way around, to find already defined
routes. This is especially useful for L<Mojolicious::Lite> apps.

Note that if L<spec_route_name|Mojolicious::Plugin::OpenAPI/spec_route_name>
then all the route names will have that value as prefix:

  spec_route_name            = "my_cool_api"
  operationId or x-mojo-name = "Foo"
  Route name                 = "my_cool_api.Foo"

You can also set "x-mojo-name" in the spec, instead of passing
L<spec_route_name|Mojolicious::Plugin::OpenAPI/spec_route_name>
to L<plugin()|Mojolicious::Plugin::OpenAPI/register>:

  {
    "swagger": "2.0",
    "info": { "version": "1.0", "title": "Some awesome API" },
    "x-mojo-name": "my_cool_api"
  }

=head2 Default response schema

A default response definition will be added to the API spec, unless it's
already defined. This schema will at least be used for invalid input (400 - Bad Request) and
invalid output (500 - Internal Server Error), but can also be used in other cases.

See L<Mojolicious::Plugin::OpenAPI/default_response_codes> and
L<Mojolicious::Plugin::OpenAPI/default_response_name> for more details on how
to configure these settings.

The response schema will be added to your spec like this, unless already defined:

  {
    ...
    "definitions": {
      ...
      "DefaultResponse": {
        "type":     "object",
        "required": ["errors"],
        "properties": {
          "errors": {
            "type":  "array",
            "items": {
              "type":       "object",
              "required":   ["message"],
              "properties": {"message": {"type": "string"}, "path": {"type": "string"}}
            }
          }
        }
      }
    }
  }

The "errors" key will contain one element for all the invalid data, and not
just the first one. The useful part for a client is mostly the "path", while
the "message" is just to add some human readable debug information for why this
request/response failed.

=head2 Rendering binary data

Rendering assets and binary data should be accomplished by using the standard
L<Mojolicious> tools:

  sub get_image {
    my $c = shift->openapi->valid_input or return;
    my $asset = Mojo::Asset::File->new(path => "image.jpeg");

    $c->res->headers->content_type("image/jpeg");
    $c->reply->asset($asset);
  }

=head1 SEE ALSO

L<Mojolicious::Plugin::OpenAPI>,
L<https://openapis.org/specification>.

=cut