sanic-org / sanic-openapi

Easily document your Sanic API with a UI
https://sanic-openapi.readthedocs.io/
MIT License
505 stars 108 forks source link

[Feature Request][OpenApi3] Add support for enums #231

Closed BilliAlpha closed 3 years ago

BilliAlpha commented 3 years ago

I am migrating my project from openapi2 and I found out that the choices parameters has disappeared in favor of enum. However it seems that this parameter is not supported in sanic-openapi.

I suppose the implementation wouldn't be more complex than adding an enum field on the Schema object.

The enum field should be supported as specified in the specifications:

The following properties are taken directly from the JSON Schema definition and follow the same specifications: [...] • enum

The JSON Schema definition of the enum field is:

The value of this keyword MUST be an array. This array SHOULD have at least one element. Elements in the array SHOULD be unique.

Elements in the array MAY be of any type, including null.

An instance validates successfully against this keyword if its value is equal to one of the elements in this keyword's array value.

https://datatracker.ietf.org/doc/html/draft-wright-json-schema-validation-00#section-5.20

ahopkins commented 3 years ago

@BilliAlpha Thanks. Would you be interested in taking a crack at a PR?

BilliAlpha commented 3 years ago

Sorry for the delay in responding, but i'll take a look at it and try something.

artcg commented 3 years ago

@BilliAlpha I havent tried using the new parameter structures yet, was planning on looking at it later today, but I find that adding the line enum: List[str] to L35 of openapi3/types.py allows me to do this

>>> from sanic_openapi.openapi3.types import Schema
>>> Schema(enum=["a"]).serialize()
{'enum': ['a']}

No idea if that solves your problem or not, feel free to try it out ...

ahopkins commented 3 years ago

@artcg That would probably be a barebones usage.

But, it probably should be:

enum: Union[List[str], Enum]

In which case we would need some logic on serialization to extract key/values from an enum.

from enum import Enum

class Color(Enum):
    RED = "red"
    GREEN = "green"
    BLUE = "blue"

print([item.value for item in Color.__members__.values()])
# ['red', 'green', 'blue']
BilliAlpha commented 3 years ago

@ahopkins I just saw your comment, I'll adapt the PR to support python Enums too.

BilliAlpha commented 3 years ago

The PR #235 was merged