Skip to content

Commit 0ebfbfd

Browse files
chrisv2carltongibson
authored andcommitted
OpenAPI: only include non-empty required property. (encode#6851)
Closes encode#6834
1 parent 335054a commit 0ebfbfd

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
"""
@@ -470,7 +474,8 @@ def _get_responses(self, path, method):
470474
for name, schema in item_schema['properties'].copy().items():
471475
if 'writeOnly' in schema:
472476
del item_schema['properties'][name]
473-
item_schema['required'] = [f for f in item_schema['required'] if f != name]
477+
if 'required' in item_schema:
478+
item_schema['required'] = [f for f in item_schema['required'] if f != name]
474479

475480
if is_list_view(path, method, self.view):
476481
response_schema = {

tests/schemas/test_openapi.py

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

145+
def test_empty_required(self):
146+
path = '/'
147+
method = 'POST'
148+
149+
class Serializer(serializers.Serializer):
150+
read_only = serializers.CharField(read_only=True)
151+
write_only = serializers.CharField(write_only=True, required=False)
152+
153+
class View(generics.GenericAPIView):
154+
serializer_class = Serializer
155+
156+
view = create_view(
157+
View,
158+
method,
159+
create_request(path)
160+
)
161+
inspector = AutoSchema()
162+
inspector.view = view
163+
164+
request_body = inspector._get_request_body(path, method)
165+
# there should be no empty 'required' property, see #6834
166+
assert 'required' not in request_body['content']['application/json']['schema']
167+
168+
for response in inspector._get_responses(path, method).values():
169+
assert 'required' not in response['content']['application/json']['schema']
170+
145171
def test_response_body_generation(self):
146172
path = '/'
147173
method = 'POST'

0 commit comments

Comments
 (0)