Skip to content

OpenAPI: only include non-empty required property. #6851

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 7, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 9 additions & 4 deletions rest_framework/schemas/openapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -381,10 +381,14 @@ def _map_serializer(self, serializer):
self._map_field_validators(field.validators, schema)

properties[field.field_name] = schema
return {
'required': required,
'properties': properties,

result = {
'properties': properties
}
if len(required) > 0:
result['required'] = required

return result

def _map_field_validators(self, validators, schema):
"""
Expand Down Expand Up @@ -470,7 +474,8 @@ def _get_responses(self, path, method):
for name, schema in item_schema['properties'].copy().items():
if 'writeOnly' in schema:
del item_schema['properties'][name]
item_schema['required'] = [f for f in item_schema['required'] if f != name]
if 'required' in item_schema:
item_schema['required'] = [f for f in item_schema['required'] if f != name]

if is_list_view(path, method, self.view):
response_schema = {
Expand Down
26 changes: 26 additions & 0 deletions tests/schemas/test_openapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,32 @@ class View(generics.GenericAPIView):
assert request_body['content']['application/json']['schema']['required'] == ['text']
assert list(request_body['content']['application/json']['schema']['properties'].keys()) == ['text']

def test_empty_required(self):
path = '/'
method = 'POST'

class Serializer(serializers.Serializer):
read_only = serializers.CharField(read_only=True)
write_only = serializers.CharField(write_only=True, required=False)

class View(generics.GenericAPIView):
serializer_class = Serializer

view = create_view(
View,
method,
create_request(path)
)
inspector = AutoSchema()
inspector.view = view

request_body = inspector._get_request_body(path, method)
# there should be no empty 'required' property, see #6834
assert 'required' not in request_body['content']['application/json']['schema']

for response in inspector._get_responses(path, method).values():
assert 'required' not in response['content']['application/json']['schema']

def test_response_body_generation(self):
path = '/'
method = 'POST'
Expand Down