Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow the specification to be specified as a URL. #1871

Merged
merged 4 commits into from
Feb 18, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion connexion/middleware/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -408,7 +408,11 @@ def add_api(
if self.middleware_stack is not None:
raise RuntimeError("Cannot add api after an application has started")

if isinstance(specification, (pathlib.Path, str)):
if isinstance(specification, str) and (
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you add in the docstrings that this can be a URL? The docstring is repeated in a couple of places across the code base, so would be good to do a find and replace.

Probably also good to explicitly mention this in the CLI docs.

specification.startswith("http://") or specification.startswith("https://")
):
pass
elif isinstance(specification, (pathlib.Path, str)):
specification = t.cast(pathlib.Path, self.specification_dir / specification)

# Add specification as file to watch for reloading
Expand Down
17 changes: 17 additions & 0 deletions connexion/spec.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,14 @@
import os
import pathlib
import pkgutil
import tempfile
import typing as t
from collections.abc import Mapping
from urllib.parse import urlsplit

import jinja2
import jsonschema
import requests
import yaml
from jsonschema import Draft4Validator
from jsonschema.validators import extend as extend_validator
Expand Down Expand Up @@ -158,6 +160,17 @@ def from_file(cls, spec, *, arguments=None, base_uri=""):
spec = cls._load_spec_from_file(arguments, specification_path)
return cls.from_dict(spec, base_uri=base_uri)

@classmethod
def from_url(cls, spec, *, arguments=None, base_uri=""):
"""
Takes in a path to a YAML file, and returns a Specification
"""
spec_content = requests.get(spec).content
with tempfile.NamedTemporaryFile() as tfile:
tfile.write(spec_content)
tfile.flush()
return cls.from_file(tfile.name, arguments=arguments, base_uri=base_uri)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we reuse the code we already use to resolve remote references?

def __call__(self, uri):
response = requests.get(uri)
response.raise_for_status()
data = io.StringIO(response.text)
with contextlib.closing(data) as fh:
return yaml.load(fh, ExtendedSafeLoader)

I like that it raises a clear error for non-successful requests and doesn't use a tempfile.


@staticmethod
def _get_spec_version(spec):
try:
Expand Down Expand Up @@ -200,6 +213,10 @@ def clone(self):

@classmethod
def load(cls, spec, *, arguments=None):
if isinstance(spec, str) and (
spec.startswith("http://") or spec.startswith("https://")
):
return cls.from_url(spec, arguments=arguments)
if not isinstance(spec, dict):
base_uri = f"{pathlib.Path(spec).parent}{os.sep}"
return cls.from_file(spec, arguments=arguments, base_uri=base_uri)
Expand Down
36 changes: 36 additions & 0 deletions tests/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,42 @@ def test_api_base_path_slash():
assert api.blueprint.url_prefix == ""


def test_remote_api():
api = FlaskApi(
Specification.load(
"https://raw.githubusercontent.com/spec-first/connexion/165a915/tests/fixtures/simple/swagger.yaml"
),
base_path="/api/v1.0",
)
assert api.blueprint.name == "/api/v1_0"
assert api.blueprint.url_prefix == "/api/v1.0"

api2 = FlaskApi(
Specification.load(
"https://raw.githubusercontent.com/spec-first/connexion/165a915/tests/fixtures/simple/swagger.yaml"
)
)
assert api2.blueprint.name == "/v1_0"
assert api2.blueprint.url_prefix == "/v1.0"

api3 = FlaskApi(
Specification.load(
"https://raw.githubusercontent.com/spec-first/connexion/165a915/tests/fixtures/simple/openapi.yaml"
),
base_path="/api/v1.0",
)
assert api3.blueprint.name == "/api/v1_0"
assert api3.blueprint.url_prefix == "/api/v1.0"

api4 = FlaskApi(
Specification.load(
"https://raw.githubusercontent.com/spec-first/connexion/165a915/tests/fixtures/simple/openapi.yaml"
)
)
assert api4.blueprint.name == "/v1_0"
assert api4.blueprint.url_prefix == "/v1.0"


def test_template():
api1 = FlaskApi(
Specification.load(
Expand Down
Loading