Home > OS >  Hop to specify the key in openAPI JSON whose name is not static
Hop to specify the key in openAPI JSON whose name is not static

Time:09-29

I want to create a JSON with openAPI specification. Example payload format to api/endpoint is as below,

"abc": {"name": "PA", "id": "21"}

So here is the openapi JSON format,

{
  "openapi": "3.0.0",
  "info": {...},
  "paths": {
    "api/endpoint": {
       "put": {
         "requestBody": {
           "required": true,
           "content": {
             "application/json": {
               "schema": {
                 "$ref": "#/components/schemas/putSchema"
               }
             }
           }
         }
       }
     }
  },
  "components": {
    "schemas": {
      "putSchema": {
        "abc": {        ----------> * 
          "type": "object",
          "properties": {
            "name": {...},
            "id": {...}
          }
        }
      }
    }
  }
}

But my payload can vary like,

"abc": {"name": "PA", "id": "21"}

"xyz": {"name": "ST", "id": "35"}

"def": {"name": "UV", "id": "94"}

Not sure how to define the JSON format for dynamic key name (here, abc/xyz/def) - (ie) what to fill in the place * in JSON).

So my query is how to specify the key in JSON whose name is not static.

CodePudding user response:

In your example, putSchema is a string-to-object map, where "abc"/"xyz"/etc. is the key in the map. Maps are defined by using the additionalProperties keyword:

"putSchema": {
  "type": "object",
  "additionalProperties": {
    "type": "object",
    "properties": {
      "name": { ...},
      "id": { ... }
    }
  }
}

If your payload has only one root key (e.g. just "abc" but not "abc" and "xyz" at the same time), you can add "maxProperties": 1 to your putSchema to limit the number of the root keys.

  • Related