jhthorsen / openapi-client

A client for talking to an Open API powered server
11 stars 17 forks source link

base_url for openapi v3 services #31

Closed pplu closed 3 years ago

pplu commented 3 years ago

Hello,

I'm running a local dev server on port 3000 with an openapi v3 spec. OpenAPI::Client was attempting to connect to localhost:80

The problem seems to strive in the fact that openapi v3 doesn't have basePath or host attributes, so OpenAPI::Client is defaulting to http://localhost, instead of picking up the info from the servers array.

I've "fixed" this problem for my specific use case with the following:

has base_url => sub {
  my $self    = shift;
  my $schema  = $self->validator;
  my $schemes = $schema->get('/schemes') || [];

  return Mojo::URL->new($schema->get('/servers/0/url'));
pplu commented 3 years ago

Hi,

Trying to use a non locally patched version of OpenAPI::Client, I finally got my code to work in the following way:

$client = OpenAPI::Client->new("http://localhost:5000/api.json");
$client->base_url(Mojo::URL->new($client->validator->get('/servers/0/url')));

So this is a way to use OpenAPI::Client with openapi v3 definitions without patching it.

@jhthorsen wanted you to know that while testing strategies, I've found that passing a base_url string as documented here: https://metacpan.org/pod/OpenAPI::Client#Custom-server-URL

$client = OpenAPI::Client->new("http://localhost:5000/api.json", base_url => 'http://localhost:5000/api');

will fail with:

Can't locate object method "clone" via package "http://localhost:5000/api" (perhaps you forgot to load "http://localhost:5000/api"?) at /home/pplu/biteright/api-test/local/lib/perl5/OpenAPI/Client.pm line 122.

because base_url is expected to be a Mojo::URL object. It would be nice if the base_url setter casted a string into a Mojo::URL object.

Also it would be nice to have OpenAPI::Client use '/servers/0/url' automatically if it detects it. Would you find a patch for that interesting?

abraxxa commented 3 years ago

Same issue here.

jhthorsen commented 3 years ago

This is now fixed and a new version of OpenAPI::Client will be available soon.