Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
openapi: Correctly encode object and array parameters.
orientor166314de78f3
diff --git a/zerver/openapi/curl_param_value_generators.py b/zerver/openapi/curl_param_value_generators.pyindex b6ebadd67a2..ad03ae3d799 100644--- a/zerver/openapi/curl_param_value_generators.py+++ b/zerver/openapi/curl_param_value_generators.py@@ -46,7 +46,10 @@ def patch_openapi_example_values(entry: str, params: List[Dict[str, Any]],for param in params:param_name = param["name"]if param_name in realm_example_values:- param["example"] = realm_example_values[param_name]+ if 'content' in param:+ param['content']['application/json']['example'] = realm_example_values[param_name]+ else:+ param["example"] = realm_example_values[param_name]if request_body is not None:properties = request_body["content"]["multipart/form-data"]["schema"]["properties"]diff --git a/zerver/openapi/markdown_extension.py b/zerver/openapi/markdown_extension.pyindex 861e25f9bf6..acf0bdc8e7f 100644--- a/zerver/openapi/markdown_extension.py+++ b/zerver/openapi/markdown_extension.py@@ -203,6 +203,8 @@ value for the {param_name} parameter. Without this we cannot automatically genercURL example."""raise ValueError(msg)ordered_ex_val_str = json.dumps(example_value, sort_keys=True)+ # We currently don't have any non-JSON encoded arrays.+ assert(jsonify)if curl_argument:return f" --data-urlencode {param_name}='{ordered_ex_val_str}'"return ordered_ex_val_str # nocoveragediff --git a/zerver/openapi/zulip.yaml b/zerver/openapi/zulip.yamlindex 0143286b1a8..947a03fc166 100644--- a/zerver/openapi/zulip.yaml+++ b/zerver/openapi/zulip.yaml@@ -531,12 +531,14 @@ paths:description: |The narrow where you want to fetch the messages from. See how to[construct a narrow](/api/construct-narrow).- schema:- type: array- items:- type: object- default: []- example: [{"operand": "Denmark", "operator": "stream"}]+ content:+ application/json:+ schema:+ type: array+ items:+ type: object+ default: []+ example: [{"operand": "Denmark", "operator": "stream"}]- $ref: '#/components/parameters/ClientGravatar'- name: apply_markdownin: query@@ -1069,11 +1071,13 @@ paths:in: querydescription: |An array containing the IDs of the target messages.- schema:- type: array- items:- type: integer- example: [4, 8, 15]+ content:+ application/json:+ schema:+ type: array+ items:+ type: integer+ example: [4, 8, 15]required: true- name: opin: query@@ -1233,21 +1237,25 @@ paths:- name: msg_idsin: querydescription: List of IDs for the messages to check.- schema:- type: array- items:- type: integer- example: [31, 32]+ content:+ application/json:+ schema:+ type: array+ items:+ type: integer+ example: [31, 32]required: true- name: narrowin: querydescription: A structure defining the narrow to check against. See how to[construct a narrow](/api/construct-narrow).- schema:- type: array- items:- type: object- example: [{'operator': 'has', 'operand': 'link'}]+ content:+ application/json:+ schema:+ type: array+ items:+ type: object+ example: [{'operator': 'has', 'operand': 'link'}]required: trueresponses:'200':@@ -1677,21 +1685,22 @@ paths:in: querydescription: |A dictionary containing the to be updated custom profile field data for the user.- schema:- type: array- items:- type: object-- example: [- {- "id": 4,- "value": "vim"- },- {- "id": 5,- "value": "1909-04-05"- },- ]+ content:+ application/json:+ schema:+ type: array+ items:+ type: object+ example: [+ {+ "id": 4,+ "value": "vim"+ },+ {+ "id": 5,+ "value": "1909-04-05"+ },+ ]required: falseresponses:@@ -2408,16 +2417,18 @@ paths:- name: subscriptionsin: querydescription: |- "A list of dictionaries containing the the key `name` and value+ A list of dictionaries containing the the key `name` and valuespecifying the name of the stream to subscribe. If the stream does notexist a new stream is created. The description of the stream created canbe specified by setting the dictionary key `description` with anappropriate value.- schema:- type: array- items:- type: object- example: [{"name": "Verona", "description": "Italian City"}]+ content:+ application/json:+ schema:+ type: array+ items:+ type: object+ example: [{"name": "Verona", "description": "Italian City"}]required: true- $ref: '#/components/parameters/Principals'- name: authorization_errors_fatal@@ -2528,11 +2539,13 @@ paths:in: querydescription: |A list of stream names to unsubscribe from.- schema:- type: array- items:- type: string- example: ['Verona', 'Denmark']+ content:+ application/json:+ schema:+ type: array+ items:+ type: string+ example: ['Verona', 'Denmark']required: false- name: addin: query@@ -2540,28 +2553,30 @@ paths:A list of objects describing which streams to subscribe to, optionallyincluding per-user subscription parameters (e.g. color) and if thestream is to be created, its description.- schema:- type: array- items:- type: object- properties:- name:- type: string- color:- type: string- description:- type: string- example:- [- {- "name": "Verona"- },- {- "name": "Denmark",- "color": "#e79ab5",- "description": "A Scandinavian country",- }- ]+ content:+ application/json:+ schema:+ type: array+ items:+ type: object+ properties:+ name:+ type: string+ color:+ type: string+ description:+ type: string+ example:+ [+ {+ "name": "Verona"+ },+ {+ "name": "Denmark",+ "color": "#e79ab5",+ "description": "A Scandinavian country",+ }+ ]required: falseresponses:'200':@@ -2643,11 +2658,13 @@ paths:description: |A list of stream names to unsubscribe from. This parameter is called`streams` in our Python API.- schema:- type: array- items:- type: string- example: ['Verona', 'Denmark']+ content:+ application/json:+ schema:+ type: array+ items:+ type: string+ example: ['Verona', 'Denmark']required: true- $ref: '#/components/parameters/Principals'responses:@@ -2908,11 +2925,13 @@ paths:each subscription. Each object represents a subscription, and must havea `stream_id` key that identifies the stream, as well as the `property`being modified and its new `value`.- schema:- type: array- items:- type: object- example: [{"stream_id": 1, "property": "pin_to_top", "value": true}, {"stream_id": 3, "property": "color", "value": '#f00f00'}]+ content:+ application/json:+ schema:+ type: array+ items:+ type: object+ example: [{"stream_id": 1, "property": "pin_to_top", "value": true}, {"stream_id": 3, "property": "color", "value": '#f00f00'}]required: trueresponses:'200':@@ -3148,7 +3167,6 @@ paths:default: falseexample: true- $ref: '#/components/parameters/Event_types'- example: ['message']- name: all_public_streamsin: querydescription: |@@ -3190,12 +3208,14 @@ paths:to optimize network performance. This is an important optimizationin organizations with 10,000s of users.New in Zulip 3.0 (feature level 18).- schema:- type: object- example:- {- "notification_settings_null": true- }+ content:+ application/json:+ schema:+ type: object+ example:+ {+ "notification_settings_null": true+ }- name: fetch_event_typesin: querydescription: |@@ -3203,11 +3223,13 @@ paths:`fetch_event_types` are used to fetch initial data. If`fetch_event_types` is not provided, `event_types` is used and if`event_types` is not provided, this parameter defaults to `None`.- schema:- type: array- items:- type: string- example: ['message']+ content:+ application/json:+ schema:+ type: array+ items:+ type: string+ example: ['message']- $ref: '#/components/parameters/Narrow'responses:'200':@@ -4071,11 +4093,13 @@ paths:**Changes**: Before Zulip 2.0, this parameter accepted only a JSON-encodedlist of email addresses. Support for the email address-based format wasremoved in Zulip 3.0 (feature level 11).- schema:- type: array- items:- type: integer- example: [9, 10]+ content:+ application/json:+ schema:+ type: array+ items:+ type: integer+ example: [9, 10]required: trueresponses:'200':@@ -4115,11 +4139,13 @@ paths:description: |An array containing the user IDs of the initial members for thenew user group.- schema:- type: array- items:- type: integer- example: [1, 2, 3, 4]+ content:+ application/json:+ schema:+ type: array+ items:+ type: integer+ example: [1, 2, 3, 4]required: trueresponses:'200':@@ -4299,7 +4325,6 @@ paths:parameters:- $ref: '#/components/parameters/Narrow'- $ref: '#/components/parameters/Event_types'- example: ['message']security:- basicAuth: []responses:@@ -5004,10 +5029,13 @@ components:your client in your client code. For most applications, oneis only interested in messages, so one specifies:`event_types=['message']`- schema:- type: array- items:- type: string+ content:+ application/json:+ schema:+ type: array+ items:+ type: string+ example: ['message']required: falseNarrow:name: narrow@@ -5019,14 +5047,16 @@ components:would specify `narrow=[['stream', 'Denmark']]`. Anotherexample is `narrow=[['is', 'private']]` for private messages.Default is `[]`.- schema:- type: array- items:- type: array- items:- type: string- default: []- example: [['stream', 'Denmark']]+ content:+ application/json:+ schema:+ type: array+ items:+ type: array+ items:+ type: string+ default: []+ example: [['stream', 'Denmark']]required: falseGroupId:name: group_id@@ -5212,13 +5242,15 @@ components:not provided, then the requesting user/bot is subscribed.**Changes**: The integer format is new in Zulip 3.0 (Feature level 9).- schema:- type: array- items:- oneOf:- - type: string- - type: integer- example: ['[email protected]']+ content:+ application/json:+ schema:+ type: array+ items:+ oneOf:+ - type: string+ - type: integer+ example: ['[email protected]']ReactionType:name: reaction_typein: querydiff --git a/zerver/tests/test_openapi.py b/zerver/tests/test_openapi.pyindex 0a0b4034083..cd8f71bdf41 100644--- a/zerver/tests/test_openapi.py+++ b/zerver/tests/test_openapi.py@@ -484,14 +484,25 @@ do not match the types declared in the implementation of {function.__name__}.\n"Otherwise, we print out the exact differences for convenient debugging and raise anAssertionError. """openapi_params: Set[Tuple[str, Union[type, Tuple[type, object]]]] = set()+ json_params: Dict[str, Union[type, Tuple[type, object]]] = dict()for element in openapi_parameters:name: str = element["name"]schema = {}if "content" in element:+ # The only content-type we use in our API is application/json.+ assert "schema" in element["content"]["application/json"]+ # If content_type is application/json, then the+ # parameter needs to be handled specially, as REQ can+ # either return the application/json as a string or it+ # can either decode it and return the required+ # elements. For example `to` array in /messages: POST+ # is processed by REQ as a string and then its type is+ # checked in the view code.+ #+ # Meanwhile `profile_data` in /users/{user_id}: GET is+ # taken as array of objects. So treat them seperately.schema = element["content"]["application/json"]["schema"]- # If content_type is application/json then the- # data type is essentially string.- openapi_params.add((name, VARMAP["string"]))+ json_params[name] = schema_type(schema)continueelse:schema = element["schema"]@@ -529,8 +540,28 @@ do not match the types declared in the implementation of {function.__name__}.\n"vtype = self.get_standardized_argument_type(function.__annotations__[vname])vname = defval.post_var_name # type: ignore[attr-defined] # See zerver/lib/request.py+ if vname in json_params:+ # Here we have two cases. If the the REQ type is+ # string then there is no point in comparing as+ # JSON can always be returned as string. Ideally,+ # we wouldn't use REQ for a JSON object without a+ # validator in these cases, but it does happen.+ #+ # If the REQ type is not string then, insert the+ # REQ and OPENAPI data types of the variable in+ # the respective sets so that they can be dealt+ # with later. In either case remove the variable+ # from `json_params`.+ if vtype == str:+ json_params.pop(vname, None)+ continue+ else:+ openapi_params.add((vname, json_params[vname]))+ json_params.pop(vname, None)function_params.add((vname, vtype))+ # After the above operations `json_params` should be empty.+ assert(len(json_params) == 0)diff = openapi_params - function_paramsif diff: # nocoverageself.render_openapi_type_exception(function, openapi_params, function_params, diff)@@ -763,11 +794,15 @@ class TestCurlExampleGeneration(ZulipTestCase):"name": "param1","in": "query","description": "An object",- "schema": {- "type": "object",- },- "example": {- "key": "value",+ "content": {+ "application/json": {+ "schema": {+ "type": "object"+ },+ "example": {+ "key": "value",+ }+ }},"required": True,},@@ -798,13 +833,17 @@ class TestCurlExampleGeneration(ZulipTestCase):"name": "param2","in": "query","description": "An object",- "schema": {- "type": "object",- },- "example": {- "key": "value",- },"required": True,+ "content": {+ "application/json": {+ "schema": {+ "type": "object"+ },+ "example": {+ "key": "value",+ }+ }+ },},],},