W2a
W2a

Reputation: 776

sanic - How to specify required JSON?

I would like to specify the required JSON for a controller get/post methods in order for it to show in SwaggerUI.

For example, I want request.json to look like this:

{
  'key1': <int>,
  'key2': <string>
}

I initialize SwaggerUI like this:

from sanic_openapi import swagger_blueprint, openapi_blueprint

app = Sanic(__name__)

# Set up SwaggerUI
app.blueprint(openapi_blueprint)
app.blueprint(swagger_blueprint)

How can I make both keys show up in parameters? enter image description here

Upvotes: 0

Views: 1172

Answers (3)

daclac
daclac

Reputation: 91

if you are reading this and wondering what happened to @doc and sanic-openapi, Sanic Extensions took over, and sanic-openapi is now deprecated .

You can accomplish the same thusly:

from sanic_ext import openapi
@app.route("/endpoint_printrrr")
@openapi.summary('Endpoint goes brrr')
@openapi.parameter(parameter=Parameter("issue_id", schema=str, deprecated=False))
async def endpoint_printrrr(request: Request) -> JSONResponse:
    ...codez

May the Lord God bless and keep you in Jesus Christ - daclac

Upvotes: 0

AlexB
AlexB

Reputation: 1

You did not see this params in swagger because your get method is on class. Sanic-openapi and Sanic-swagger does not support class based views yet. :(

Upvotes: 0

Oluwafemi Sule
Oluwafemi Sule

Reputation: 38922

There is sanic_openapi.doc.consumes decorator for decorating view functions to document their input. This naming of the decorator function follows from the OpenAPI specification.

Here is one way to apply it:

@app.post('/recording_test')
@doc.summary('Tests a recording')
@doc.consumes({'key1': str, 'key2': int}, location='body')
async def create_recording_test(request):
    ...

You can model your input using a class.

class RecordingTest:
    key1 = str
    key2 = int

Use the modeled input above in the following manner

@app.post('/recording_test')
@doc.summary('Tests a recording')
@doc.consumes(RecordingTest, location='body')
async def create_recording_test(request):
    ...

Upvotes: 1

Related Questions