jhthorsen / mojolicious-plugin-openapi

OpenAPI / Swagger plugin for Mojolicious
54 stars 44 forks source link

Code in SYNOPSYS doesn't work #57

Closed pavelsr closed 6 years ago

pavelsr commented 6 years ago
use Mojolicious::Lite;

# 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->validation->param("body")};

  # 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://main/api.json"};
app->start;

__DATA__
@@ api.json
{
  "swagger" : "2.0",
  "info" : { "version": "0.8", "title" : "Pets" },
  "schemes" : [ "http" ],
  "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" }
          }
        }
      }
    }
  }
}

If simply run this code with morbo you will get a JSON::Validator error:

api.json could not be found in __DATA__ section of main. at /usr/local/share/perl/5.22.1/JSON/Validator.pm line 212
jhthorsen commented 6 years ago

It's because morbo puts the code inside a Mojo::Server::Sandbox::... package. Not sure if I care enough to fix this since I think it will be confusing to throw package whatever; before __DATA__, and from my point of view, the code is supposed to be an illustration and not something you copy/paste.

I think I would rather delete the whole example and refer to https://metacpan.org/pod/distribution/Mojolicious-Plugin-OpenAPI/lib/Mojolicious/Plugin/OpenAPI/Guides/Tutorial.pod or https://mojolicious.io/blog/2017/12/22/day-22-how-to-build-a-public-rest-api/

jhthorsen commented 6 years ago

I'm closing this, since I don't find it important enough to fix.