Skip to content

Add OpenAPI registration module #40

Closed

Description

@uniqueg

Problem

Users should have the ability to

  • register multiple OpenAPI specs passed as absolute paths (relative paths, as currently defined in the corresponding cwl-WES, proTES and proWES modules, won't work easily because the anchor point relative to which relative paths are to be interpreted would be inside the app's directory tree and NOT in the one of the FOCA package)
  • provide OpenAPI specs of version 3 or version 2; providing specs of both versions for the same service should be supported
  • provide OpenAPI specs in either YAML or JSON formats; as connexion requires YAML format, specs provided in JSON format will need to be dumped in YAML format
  • add one or more fields to the root of the specification or overwrite an existing specs section, e.g., to allow the addition (or replacement) of a security (OpenAPI 3) or securityDefinitions (OpenAPI 2) field
  • add fields to the Operation Object of each Path Info Object in the required paths field (or overwrite them), which is required for both OpenAPI 3 and OpenAPI 2; this is mostly to support the addition (or replacement) of the x-swagger-router-controller field
  • provide output file paths for each modified spec file (ignore if no modifications are done, i.e., if a YAML file is provided and no fields are added)

Proposed solution

  • Nothing particular has to be done to support providing both OpenAPI 2 and 3 specs, as connexion already supports that since version v2.0.0

  • For the specs format, it should first be tried to yaml.safe_load() each spec, and if that doesn't work, json.load() them; if that doesn't work either (i.e., both YAML and JSON loaders fail), an error InvalidSpecs (needs to be defined in the errors.py module) should be raised.
    It should look something like this:

    import json
    
    import yaml
    
    from foca.errors.erros import InvalidSpecs
    
    try:
        specs = yaml.safe_load(specs_file)
    except yaml.parser.ParserError:
        try:
            specs = json.load(specs_file)
        except json.decoder.JSONDecodeError:
            raise InvalidSpecs

    At this point, if no error is raised, we will now have a dict() with the OpenAPI contents.

  • For adding content to the root of the specs (or replace a section), just loop over the list of dictionaries to be added and update the specs dictionary with the like so:

    # example values:
    # specs = {'something': 'something'}
    # append = [{'other_thing': 'other_thing'}, {'yet_another_thing': {'a': 1, 'b': 2}}]
    for item in append:
        specs.update(item)
  • For adding fields to all Operation Objects (or replacing them, if they already exist), one could do something like:

    # example values:
    # field = 'x-swagger-router-controller'
    # value = 'controllers.ga4gh.wes'
    try:
        for path_item_object in specs['paths'].values():
            for operation_object in path_item_object.values():
                operation_object[field] = value
    except (AttributeError, KeyError):
        raise InvalidSpecs  
  • Finally, if specs have been modified or are supplied in JSON (which connexion cannot process), the specs dictionary has to be dumped back to a file with yaml.safe_dump(specs, output_file); the behavior for output file paths for modified spec files should be such that if no value is supplied, the file extension of the original input file (e.g., /path/to/my/specs.json) should be stripped (to yield, e.g., /path/to/my/specs) and a suffix with .yaml extension appended (parameterize, but do not make available for the user; use .modified.yaml as default, i.e., the previous example would yield /path/to/my/specs.modified.yaml); if a file path for the output file is specified, of course the contents of specs should be dumped to that.

  • To simplify usage and allow validation of the parameters that need to be passed, a class could be defined for the config params for the spec files (i.e., the output file path, the stuff to be added to the root and to the Operation Objects); a call to its constructor could look something like this:

    my_specs_config = OpenAPIConfig(
        out_file='/path/to/my/modified/specs.yaml',
        append=[
            {
                'security':
                    'jwt':
                        'type': 'apiKey',
                        'name': 'Authorization',
                        'in': 'header',
            },
            {
               'my_other_root_field': 'some_value',
            },
        ],
        add_operation_fields = {
            'x-swagger-router-controller': 'controllers.ga4gh.wes',
            'some-other-custom-field': 'some_value',
        },      
    )

    All fields should be optional, so that OpenAPIConfig() can be called without any parameters.
    The register_openapi() function could then be called with something like this:

    register_openapi({
        '/path/to/my/specs.yaml': my_specs_config,
        '/path/to/my/other_specs.json': OpenAPICOnfig(),
    })

    This would register two OpenAPI spec files with connexion:

    • The first one is a YAML file that has security definitions and another field appended to its root, and two fields added to each operation; the modified file is written to the specified output file path
    • The second one is a JSON file that is converted to YAML but has no other additions; as no output file path is specified for the modified file, it will be written to the same directory that the spec file was read from (/path/to/my/other_specs.json), but under a modified name: /path/to/my/other_specs.modified.yaml

    In practice, of course, the app admin (i.e., the person who wants to, say, set up cwl-WES or another FOCA-based service) would have all these values in a properly structured FOCA-compatible app config, so he/she would just pass something like this to the FOCA constructor (which we still have to implement):

    import yaml
    
    with open('/path/to/config.yaml') as config_file:
        config = yaml.safe_load(config_file)
    
    app = FOCA(**config)

    That should be pretty much all the code that is needed in the final app. Of course we will need to work on the model/class to not only configure OpenAPI specs, but also set up custom errors and handlers, configure the database etc.

  • Make sure to properly document the behavior in the functions/methods docstrings and of course write tests for the expected behavior

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

priority: mediumtype: featureworkload: days

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions