如何在Django的Swagger中通过coreapi.Field添加请求体示例数据
Solution
To add your desired example JSON data to the request body in Swagger, you'll need to make two key adjustments to your existing coreapi.Field definition:
- Correct the field type from
"string"to"object"(since your request body is a JSON object, not a string). - Include the example data directly in the
coreschema.Objectdefinition (this is supported in your version ofcoreschemaused bydjango-rest-swagger).
Here's the modified code for your ParseResume view:
from rest_framework.schemas import AutoSchema from rest_framework.views import APIView from rest_framework.permissions import AllowAny from rest_framework.response import Response import coreapi import coreschema class ParseResume(APIView): permission_classes = [AllowAny] schema = AutoSchema( manual_fields=[ coreapi.Field( "data", required=True, location="body", description='Send Json Data', type="object", # Changed from "string" to "object" schema=coreschema.Object( # Add your example data as a Python dictionary here example={ "id": "56-df-pt", "fname": "John", "lname": "Doe", "experience": { "employee": "Company X", "period": "1996 - 2002", "engaged_in": [ { "work": "Jr. Manager", "team_size": 5, "time": "Sep. 1996 - Dec. 1998" }, { "work": "Sr. Manager", "team_size": 5, "time": "Jan. 1999 - Dec. 2002" } ] } } ), ) ] ) def post(self, request): data = request.data response_data = SetConnections.parse_resume(data) return Response(response_data)
Key Explanations:
- Type Correction: Changing
type="string"totype="object"tells Swagger that the request body is a structured JSON object, not a plain string. This ensures the Swagger UI renders a proper JSON editor instead of a text input. - Example Data: The
exampleparameter incoreschema.Object()accepts a Python dictionary that gets converted to JSON in the Swagger UI. This will appear as a pre-filled example in the request body section of your API documentation.
This approach works seamlessly with your current versions of Django (2.2.4), DRF (3.10.2), and django-rest-swagger (2.2.0) since coreschema 0.0.4 (the version used by django-rest-swagger 2.2.0) supports the example parameter for object schemas.
Content of the question originates from Stack Exchange, question author Rahul Chakraborty
相关产品推荐
相关产品推荐

