-
Notifications
You must be signed in to change notification settings - Fork 155
new: Add support for loading JSON OpenAPI spec files #629
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
Merged
lgarber-akamai
merged 2 commits into
linode:dev
from
lgarber-akamai:new/spec-target-repoint
Oct 29, 2024
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,7 @@ | ||
| FROM python:3.11-slim AS builder | ||
|
|
||
| ARG linode_cli_version | ||
|
|
||
| ARG github_token | ||
|
|
||
| WORKDIR /src | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -2,11 +2,17 @@ | |
| Responsible for managing spec and routing commands to operations. | ||
| """ | ||
|
|
||
| import contextlib | ||
| import json | ||
| import os | ||
| import pickle | ||
| import sys | ||
| from json import JSONDecodeError | ||
| from sys import version_info | ||
| from typing import IO, Any, ContextManager, Dict | ||
|
|
||
| import requests | ||
| import yaml | ||
| from openapi3 import OpenAPI | ||
|
|
||
| from linodecli.api_request import do_request, get_all_pages | ||
|
|
@@ -40,11 +46,19 @@ def __init__(self, version, base_url, skip_config=False): | |
| self.config = CLIConfig(self.base_url, skip_config=skip_config) | ||
| self.load_baked() | ||
|
|
||
| def bake(self, spec): | ||
| def bake(self, spec_location: str): | ||
| """ | ||
| Generates ops and bakes them to a pickle | ||
| Generates ops and bakes them to a pickle. | ||
|
|
||
| :param spec_location: The URL or file path of the OpenAPI spec to parse. | ||
| """ | ||
| spec = OpenAPI(spec) | ||
|
|
||
| try: | ||
| spec = self._load_openapi_spec(spec_location) | ||
| except Exception as e: | ||
| print(f"Failed to load spec: {e}") | ||
| sys.exit(ExitCodes.REQUEST_FAILED) | ||
|
|
||
| self.spec = spec | ||
| self.ops = {} | ||
| ext = { | ||
|
|
@@ -206,3 +220,85 @@ def user_agent(self) -> str: | |
| f"linode-api-docs/{self.spec_version} " | ||
| f"python/{version_info[0]}.{version_info[1]}.{version_info[2]}" | ||
| ) | ||
|
|
||
| @staticmethod | ||
| def _load_openapi_spec(spec_location: str) -> OpenAPI: | ||
| """ | ||
| Attempts to load the raw OpenAPI spec (YAML or JSON) at the given location. | ||
|
|
||
| :param spec_location: The location of the OpenAPI spec. | ||
| This can be a local path or a URL. | ||
|
|
||
| :returns: A tuple containing the loaded OpenAPI object and the parsed spec in | ||
| dict format. | ||
| """ | ||
|
|
||
| with CLI._get_spec_file_reader(spec_location) as f: | ||
| parsed = CLI._parse_spec_file(f) | ||
|
|
||
| return OpenAPI(parsed) | ||
|
|
||
| @staticmethod | ||
| @contextlib.contextmanager | ||
| def _get_spec_file_reader( | ||
| spec_location: str, | ||
| ) -> ContextManager[IO]: | ||
|
Comment on lines
+235
to
+245
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Very cool usage of context manager! |
||
| """ | ||
| Returns a reader for an OpenAPI spec file from the given location. | ||
|
|
||
| :param spec_location: The location of the OpenAPI spec. | ||
| This can be a local path or a URL. | ||
|
|
||
| :returns: A context manager yielding the spec file's reader. | ||
| """ | ||
|
|
||
| # Case for local file | ||
| local_path = os.path.expanduser(spec_location) | ||
| if os.path.exists(local_path): | ||
| f = open(local_path, "r", encoding="utf-8") | ||
|
|
||
| try: | ||
| yield f | ||
| finally: | ||
| f.close() | ||
|
|
||
| return | ||
|
|
||
| # Case for remote file | ||
| resp = requests.get(spec_location, stream=True, timeout=120) | ||
| if resp.status_code != 200: | ||
| raise RuntimeError(f"Failed to GET {spec_location}") | ||
|
|
||
| # We need to access the underlying urllib | ||
| # response here so we can return a reader | ||
| # usable in yaml.safe_load(...) and json.load(...) | ||
| resp.raw.decode_content = True | ||
|
|
||
| try: | ||
| yield resp.raw | ||
| finally: | ||
| resp.close() | ||
|
|
||
| @staticmethod | ||
| def _parse_spec_file(reader: IO) -> Dict[str, Any]: | ||
| """ | ||
| Parses the given file reader into a dict and returns a dict. | ||
|
|
||
| :param reader: A reader for a YAML or JSON file. | ||
|
|
||
| :returns: The parsed file. | ||
| """ | ||
|
|
||
| errors = [] | ||
|
|
||
| try: | ||
| return yaml.safe_load(reader) | ||
| except yaml.YAMLError as err: | ||
| errors.append(str(err)) | ||
|
|
||
| try: | ||
| return json.load(reader) | ||
| except JSONDecodeError as err: | ||
| errors.append(str(err)) | ||
|
|
||
| raise ValueError(f"Failed to parse spec file: {'; '.join(errors)}") | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,95 @@ | ||
| { | ||
| "openapi": "3.0.1", | ||
| "info": { | ||
| "title": "API Specification", | ||
| "version": "1.0.0" | ||
| }, | ||
| "servers": [ | ||
| { | ||
| "url": "http://localhost/v4" | ||
| } | ||
| ], | ||
| "paths": { | ||
| "/foo/bar": { | ||
| "get": { | ||
| "summary": "get info", | ||
| "operationId": "fooBarGet", | ||
| "description": "This is description", | ||
| "responses": { | ||
| "200": { | ||
| "description": "Successful response", | ||
| "content": { | ||
| "application/json": { | ||
| "schema": { | ||
| "type": "object", | ||
| "properties": { | ||
| "data": { | ||
| "type": "array", | ||
| "items": { | ||
| "$ref": "#/components/schemas/OpenAPIResponseAttr" | ||
| } | ||
| }, | ||
| "page": { | ||
| "$ref": "#/components/schemas/PaginationEnvelope/properties/page" | ||
| }, | ||
| "pages": { | ||
| "$ref": "#/components/schemas/PaginationEnvelope/properties/pages" | ||
| }, | ||
| "results": { | ||
| "$ref": "#/components/schemas/PaginationEnvelope/properties/results" | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
| }, | ||
| "components": { | ||
| "schemas": { | ||
| "OpenAPIResponseAttr": { | ||
| "type": "object", | ||
| "properties": { | ||
| "filterable_result": { | ||
| "x-linode-filterable": true, | ||
| "type": "string", | ||
| "description": "Filterable result value" | ||
| }, | ||
| "filterable_list_result": { | ||
| "x-linode-filterable": true, | ||
| "type": "array", | ||
| "items": { | ||
| "type": "string" | ||
| }, | ||
| "description": "Filterable result value" | ||
| } | ||
| } | ||
| }, | ||
| "PaginationEnvelope": { | ||
| "type": "object", | ||
| "properties": { | ||
| "pages": { | ||
| "type": "integer", | ||
| "readOnly": true, | ||
| "description": "The total number of pages.", | ||
| "example": 1 | ||
| }, | ||
| "page": { | ||
| "type": "integer", | ||
| "readOnly": true, | ||
| "description": "The current page.", | ||
| "example": 1 | ||
| }, | ||
| "results": { | ||
| "type": "integer", | ||
| "readOnly": true, | ||
| "description": "The total number of results.", | ||
| "example": 1 | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,64 @@ | ||
| openapi: 3.0.1 | ||
| info: | ||
| title: API Specification | ||
| version: 1.0.0 | ||
| servers: | ||
| - url: http://localhost/v4 | ||
| paths: | ||
| /foo/bar: | ||
| get: | ||
| summary: get info | ||
| operationId: fooBarGet | ||
| description: This is description | ||
| responses: | ||
| '200': | ||
| description: Successful response | ||
| content: | ||
| application/json: | ||
| schema: | ||
| type: object | ||
| properties: | ||
| data: | ||
| type: array | ||
| items: | ||
| $ref: '#/components/schemas/OpenAPIResponseAttr' | ||
| page: | ||
| $ref: '#/components/schemas/PaginationEnvelope/properties/page' | ||
| pages: | ||
| $ref: '#/components/schemas/PaginationEnvelope/properties/pages' | ||
| results: | ||
| $ref: '#/components/schemas/PaginationEnvelope/properties/results' | ||
|
|
||
| components: | ||
| schemas: | ||
| OpenAPIResponseAttr: | ||
| type: object | ||
| properties: | ||
| filterable_result: | ||
| x-linode-filterable: true | ||
| type: string | ||
| description: Filterable result value | ||
| filterable_list_result: | ||
| x-linode-filterable: true | ||
| type: array | ||
| items: | ||
| type: string | ||
| description: Filterable result value | ||
| PaginationEnvelope: | ||
| type: object | ||
| properties: | ||
| pages: | ||
| type: integer | ||
| readOnly: true | ||
| description: The total number of pages. | ||
| example: 1 | ||
| page: | ||
| type: integer | ||
| readOnly: true | ||
| description: The current page. | ||
| example: 1 | ||
| results: | ||
| type: integer | ||
| readOnly: true | ||
| description: The total number of results. | ||
| example: 1 |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Given the new OpenAPI spec is so large, I used a ContextManager & stream here to avoid loading the spec into memory more times than we need to.