flask-smorest icon indicating copy to clipboard operation
flask-smorest copied to clipboard

Using a dict of fields for arguments

Open AbdealiLoKo opened this issue 3 years ago • 5 comments

In the docs, I see there is a way to do: @blp.arguments(PetSchema) Is there a way to simply do: @blp.arguments({'name': ma.fields.Str()}) ?

I was trying to port some of my projects from flaks-apispec to flask-smorest and in flask-apispec I was doing: @use_kwargs({'name': ma.fields.Str()}) a lot as that seemed generic and easy to define for my endpoints with simple query params. I didn't see a similar thing in smorest, and was wondering if I have to define a schema every time ?

I don't like schemas too much because they become a bit verbose for 1 or 2 arguments ... and then in cases where I need borh a query-param and a body as arguments (POST with query params) I need to define 2 schemas - which seems to be confusing

AbdealiLoKo avatar Aug 21 '20 18:08 AbdealiLoKo

We never tried to support that.

I wouldn't mind adding this feature if it is not too hard to support.

lafrech avatar Oct 02 '20 12:10 lafrech

+1

Also, currently if you want to define specific example and description for each query parameter, you have to define multiple schemas and pass them to blp.arguments separately. With the above feature, all these schema definitions would be eliminated.

technolingo avatar Feb 06 '21 15:02 technolingo

@technolingo do you mind being more explicit (with an example)? Can't you pass a single schema with each field providing its example and description?

class QueryArgsSchema(ma.Schema):
    arg1 = ma.fields.String(metadata={"description": "First arg", "example": "Example value})
    ...

lafrech avatar Mar 24 '21 23:03 lafrech

+1 for this feature. Although, for reference, you can use @blp.arguments(ma.Schema.from_dict({'name': ma.fields.Str()}))

summersz avatar Feb 07 '22 14:02 summersz

I've been trying to take over #423. The issue with from_dict is that the generated schema has a default name ("Generated") and apispec complains that Multiple schemas resolved to the name Generated.

I see no simple way to infer a better name.

There is no point adding a schema_name . At this point, the user might as well do

@blp.arguments(ma.Schema.from_dict({'name': ma.fields.Str()}, name="MeaningfulSchemaName"))

or even create a schema the normal way.

We could use a unique name generator, for instance using a global counter and use it when we build the schemas from dict. I don't really like the sound of it but I suppose users using dicts for schemas don't really care about the name.

lafrech avatar Aug 16 '23 18:08 lafrech