Last active
October 22, 2023 13:00
-
-
Save VehpuS/e81a48187c11eb4a19106a15d87e250a to your computer and use it in GitHub Desktop.
Test openapi operations schema before calling an endpoint
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
from dataclasses import dataclass | |
from typing import Any, Dict, List, Literal, Union | |
@dataclass | |
class OpenAPIOperation: | |
path: str | |
action: Union[ | |
Literal["get"], | |
Literal["post"], | |
Literal["put"], | |
Literal["delete"], | |
Literal["patch"], | |
] | |
parameters: List[str] | |
def check_api_for_ops( | |
openapi_json: Dict[str, Any], operations: List[OpenAPIOperation] | |
) -> bool: | |
for path, action, parameters in operations: | |
if path in openapi_json["paths"] and action in openapi_json["paths"][path]: | |
if "parameters" not in openapi_json["paths"][path][action]: | |
return False | |
path_parameters = [ | |
param["name"] | |
for param in openapi_json["paths"][path][action]["parameters"] | |
if "name" in param | |
] | |
for parameter in parameters: | |
if parameter not in path_parameters: | |
return False | |
else: | |
return False | |
return True |
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
import { compact, every, includes, isEmpty, map, some } from 'lodash'; | |
interface OpenAPIOperation { | |
path: string; | |
action: 'get' | 'post' | 'put' | 'delete'; | |
parameters: string[]; | |
} | |
function checkOpenApiForOps( | |
openApiJson: any, | |
operations: OpenAPIOperation[], | |
): boolean { | |
return every(operations, ({ path, action, parameters }) => { | |
if ( | |
includes(openApiJson.paths, path) && | |
openApiJson.paths?.[path]?.[action] | |
) { | |
if (!isEmpty(openApiJson.paths[path][action].parameters)) { | |
return false; | |
} | |
const pathParameters = compact( | |
map(openApiJson.paths[path][action].parameters, 'name'), | |
); | |
if ( | |
some(parameters, (parameter) => !includes(pathParameters, parameter)) | |
) { | |
return false; | |
} | |
} else { | |
return false; | |
} | |
return true; | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment