question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[BUG] OpenAPI schema is not valid

See original GitHub issue

Describe the bug

The openapi.json generated from the docs is not valid OpenAPI 3.0 schema and doesn’t pass validation. Can be checked against few available validators:

Expected behavior

Passes validation.

Environment:

  • OS: macOS
  • FastAPI Version: 0.33.0
  • Python version: 3.7.3

Additional context

After looking at the schema I found some noticeable parts:

  • Security definitions are duplicated multiple times is there are some dependencies with shared sub dependencies. In the schema it looks like:
"security": [
  {
    "My Auth": []
  },
  {
    "My Auth": []
  }
]
  • For numeric values min/max validation flags should be boolean values instead of integers:
"schema": {
  "title": "Size",
  "maximum": 100,
  "exclusiveMinimum": 0,
  "type": "integer",
  "description": "Number of records to return",
  "default": 10
}

The "exclusiveMinimum": 0, should be in fact "exclusiveMinimum": false,

  • Path parameters is referenced in multiple dependencies for a route get duplicated:
"parameters": [
  {
    "required": true,
    "schema": {
      "title": "User_Id",
      "type": "string",
      "format": "uuid"
    },
    "name": "user_id",
    "in": "path"
  },
  {
    "required": true,
    "schema": {
      "title": "User_Id",
      "type": "string",
      "format": "uuid"
    },
    "name": "user_id",
    "in": "path"
  }
]
  • References are not properly defined and thus resolved, resulting in multiple errors such as:
Missing required property: $ref at #/user/roles

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Reactions:3
  • Comments:6 (4 by maintainers)

github_iconTop GitHub Comments

1reaction
LKaycommented, Jul 19, 2019

Here is the minimal example that generates all but the $ref issues I mentioned above:

from uuid import UUID

from authlib.jose import jwt, JWTClaims
from fastapi import APIRouter, Body, Depends, Security, FastAPI
from fastapi.security import OAuth2PasswordBearer, SecurityScopes
from pydantic import BaseModel, condecimal, Decimal


class AccessToken(JWTClaims):
    pass


class AuthData(BaseModel):
    jwt: str
    claims: AccessToken


oauth_scheme = OAuth2PasswordBearer(
    tokenUrl="https://auth.domain.com/token",
    scheme_name="My Auth",
    scopes={
        "email": "Email address access"
    }
)


async def require_oauth(
        scopes: SecurityScopes,
        bearer: str = Depends(oauth_scheme)
) -> AuthData:
    claims: AccessToken = jwt.decode(bearer, "key", claims_cls=AccessToken)
    claims.validate()

    return AuthData(
        jwt=bearer,
        claims=claims
    )


class User(BaseModel):
    pass


async def current_user(*,
                       auth: AuthData = Security(require_oauth)) -> User:
    # Get user from the database based on auth claims
    return User()


async def user_exists(*,
                      user_id: UUID) -> bool:
    # Query database for existence of requested user
    return True


class BugData(BaseModel):
    positive_decimal: condecimal(gt=Decimal(0))


router = APIRouter()


@router.post(
    "/users/{user_id}/bug",
    dependencies=[
        Depends(user_exists)
    ]
)
async def bug(*,
              user_id: UUID,
              user: User = Depends(current_user),
              data: BugData = Body(...)):
    pass


app: FastAPI = FastAPI(
    title="Bug API"
)

app.include_router(
    router,
    dependencies=[
        Security(require_oauth)
    ]
)

This is simplified for the sake of reproducing but in my actual app I have quite a few routes dependencies which depend on other dependencies, similar way as current_user in the example. The schema generated from the above does’t seem to be valid.

0reactions
tiangolocommented, Feb 10, 2020

Thanks for the report @LKay ! I had to modify your example a bit to make it a minimum self-contained app, not requiring authlib to demonstrate the issue.

I wasn’t able to replicate your auth errors, I imagine it was probably fixed recently.

About exclusiveMinimum, and exclusiveMaximum, those are 2 special cases, as in previous versions of JSON Schema they were booleans. But in recent versions those are integers.

OpenAPI is based on JSON Schema, but it was based on the initial version, before that change.

So, for those 2 specific keywords, we could support a recent version of JSON Schema or the older version used by OpenAPI. FastAPI (and actually Pydantic) use the recent version of JSON Schema. This allows, for example, using the integrated schemas with tools that can generate UIs based on JSON Schema. Still, minimum and maximum work the same in both specifications, so it’s only those two specific keywords. You can track the progress about that in this issue: https://github.com/tiangolo/fastapi/issues/240

About the duplicated parameter ID in OpenAPI, that is indeed a bug 🐛 . I created a new issue with a simple example to reproduce it and an included test to verify it: #967

Also, thanks @euri10 for the help here!

I’m gonna close this issue now, let’s keep track of that bug in the new issue.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Fix Swagger Validator errors in Power Platform connectors
Use this topic during the certification process to find your Swagger Validation errors and fix it in the the connector files you submit....
Read more >
oneOf, anyOf, allOf, not - Swagger
Use the oneOf keyword to ensure the given data is valid against one of the specified schemas. ... The example above shows how...
Read more >
OpenAPI 3: Missing property "$ref" - Stack Overflow
yaml-schema: Validation schema for OpenAPI Specification 3.0.X. error message. Obviously, this error makes no sense at all, since $ref is never ...
Read more >
Parsing error(s): The input OpenAPI file is not valid for the ...
When we are validating the schema with OpenAPI specification getting the below error . One or more fields contain incorrect values:
Read more >
Handling Validation Errors - python-jsonschema
An instance was invalid under a provided schema. The information carried by an error roughly breaks down into: What Happened. Why Did It...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found