validate_api_doc.py 1.28 KB
import os
import sys

from django.core.management import BaseCommand

from openapi_spec_validator import validate_spec_url, validate_v2_spec_url
from openapi_spec_validator.exceptions import ValidationError


# from openapi_spec_validator/__main__.py
class Command(BaseCommand):
    def add_arguments(self, parser):
        parser.add_argument(
            'filename', help="Absolute or relative path to file")
        parser.add_argument(
            '--schema',
            help="OpenAPI schema (default: 3.0.0)",
            type=str,
            choices=['2.0', '3.0.0'],
            default='3.0.0')

    def handle(self, *args, **kwargs):
        filename = kwargs['filename']
        filename = os.path.abspath(filename)
        # choose the validator
        if kwargs['schema'] == '2.0':
            validate_url = validate_v2_spec_url
        elif kwargs['schema'] == '3.0.0':
            validate_url = validate_spec_url
        # validate
        try:
            validate_url('file://' + filename)
        except ValidationError as err:
            self.stdout.write(self.style.ERROR(err))
            sys.exit(1)
        except Exception as err:
            self.stdout.write(self.style.ERROR(err))
            sys.exit(2)
        else:
            self.stdout.write(self.style.SUCCESS('ok'))