Skip to content

Commit af361e6

Browse files
committed
don't add empty required property (fixes #6834)
1 parent 659375f commit af361e6

File tree

2 files changed

+35
-4
lines changed

2 files changed

+35
-4
lines changed

rest_framework/schemas/openapi.py

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -381,10 +381,14 @@ def _map_serializer(self, serializer):
381381
self._map_field_validators(field.validators, schema)
382382

383383
properties[field.field_name] = schema
384-
return {
385-
'required': required,
386-
'properties': properties,
384+
385+
result = {
386+
'properties': properties
387387
}
388+
if len(required) > 0:
389+
result['required'] = required
390+
391+
return result
388392

389393
def _map_field_validators(self, validators, schema):
390394
"""
@@ -476,7 +480,8 @@ def _get_responses(self, path, method):
476480
for name, schema in content['properties'].copy().items():
477481
if 'writeOnly' in schema:
478482
del content['properties'][name]
479-
content['required'] = [f for f in content['required'] if f != name]
483+
if 'required' in content:
484+
content['required'] = [f for f in content['required'] if f != name]
480485

481486
return {
482487
'200': {

tests/schemas/test_openapi.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,32 @@ class View(generics.GenericAPIView):
121121
assert request_body['content']['application/json']['schema']['required'] == ['text']
122122
assert list(request_body['content']['application/json']['schema']['properties'].keys()) == ['text']
123123

124+
def test_empty_required(self):
125+
path = '/'
126+
method = 'POST'
127+
128+
class Serializer(serializers.Serializer):
129+
read_only = serializers.CharField(read_only=True)
130+
write_only = serializers.CharField(write_only=True, required=False)
131+
132+
class View(generics.GenericAPIView):
133+
serializer_class = Serializer
134+
135+
view = create_view(
136+
View,
137+
method,
138+
create_request(path)
139+
)
140+
inspector = AutoSchema()
141+
inspector.view = view
142+
143+
request_body = inspector._get_request_body(path, method)
144+
# there should be no empty 'required' property, see #6834
145+
assert 'required' not in request_body['content']['application/json']['schema']
146+
147+
for response in inspector._get_responses(path, method).values():
148+
assert 'required' not in response['content']['application/json']['schema']
149+
124150
def test_response_body_generation(self):
125151
path = '/'
126152
method = 'POST'

0 commit comments

Comments
 (0)