drf-yasg
drf-yasg copied to clipboard
Support field level examples
Add support for field-level examples from meta class …
This code allows us to add field-level example
s. Usage:
class SomeSerializer(serializers.Serializer):
some_date = serializers.DateField()
class Meta:
swagger_schema_examples = {
'some_date': '2000-01-15'
}
I think something like this would be amazing.
Currently to add an example, you have to manually specify the entire schema using swagger_schema_fields
. And if you have nested objects... good luck.
class TitleSerializer(serializers.Serializer):
title = serializers.CharField()
slug = serializers.SlugField(required=False)
class Meta:
swagger_schema_fields = {
"type": openapi.TYPE_OBJECT,
"title": "Title",
"properties": {
"title": openapi.Schema(
title="Title of page",
type=openapi.TYPE_STRING,
example="Custom Example Data"
),
"slug": openapi.Schema(
title="Slug of page",
type=openapi.TYPE_STRING,
example="custom-example-data"
),
},
"required": ["title"],
}
Unless someone else knows how to add an example directly to a field?
Just found this: https://pypi.org/project/drf-yasg-examples/
It basically achieves this with an inspector that you can put into your default inspectors list.
class ExampleInspector(SerializerInspector):
def process_result(self, result, method_name, obj, **kwargs):
has_examples = hasattr(obj, "Meta") and hasattr(obj.Meta, "examples")
if isinstance(result, openapi.Schema.OR_REF) and has_examples:
schema = openapi.resolve_ref(result, self.components)
if "properties" in schema:
properties = schema["properties"]
for name in properties.keys():
if name in obj.Meta.examples:
properties[name]["example"] = obj.Meta.examples[name]
return result
SWAGGER_SETTINGS = {
"DEFAULT_FIELD_INSPECTORS": [
# The new inspector
"xx.yy.ExampleInspector",
# Defaults from drf-yasg (unmodified)
"drf_yasg.inspectors.CamelCaseJSONFilter",
"drf_yasg.inspectors.RecursiveFieldInspector",
"drf_yasg.inspectors.ReferencingSerializerInspector",
"drf_yasg.inspectors.ChoiceFieldInspector",
"drf_yasg.inspectors.FileFieldInspector",
"drf_yasg.inspectors.DictFieldInspector",
"drf_yasg.inspectors.JSONFieldInspector",
"drf_yasg.inspectors.HiddenFieldInspector",
"drf_yasg.inspectors.RelatedFieldInspector",
"drf_yasg.inspectors.SerializerMethodFieldInspector",
"drf_yasg.inspectors.SimpleFieldInspector",
"drf_yasg.inspectors.StringDefaultFieldInspector",
],
}
@zak10 thanks for the time put into this PR. Could you bring the branch up to date with the 1.21.x branch or enable me to push to it?