OpenAPI v3 offers using JSON or YAML format.
I prefer using YAML to create API specifications. YAML's readability is much better for me as an API designer.
However, sometimes I need to embed a message example whose type is object. I usually have the examples in JSON format. So I would do the following:
examples:
singlePet:
summary: Single pet
description: A request containing a single pet
value: |
{
"pets" : [
{
"petType" : "DOG",
"name" : "Ben"
}
]
}
However, such value is a string, not an object, whereas OpenAPI expects an object.
Do we have any options to embed a JSON as an example value in the YAML specification?
Currently, I convert the JSON to YAML and embed the YAML:
examples:
singlePet:
summary: Single pet
description: A request containing a single pet
value:
pets:
- petType: DOG
name: Ben
YAML is a superset of JSON. This means you can use JSON syntax for objects and arrays within a YAML document.
In your first example, you can just remove the | after the value: to keep the example value as an object.
The following are equivalent:
examples:
singlePet:
summary: Single pet
description: A request containing a single pet
value:
{
"pets" : [
{
"petType" : "DOG",
"name" : "Ben"
}
]
}
examples:
singlePet:
summary: Single pet
description: A request containing a single pet
value:
pets:
- petType: DOG
name: Ben
Alternatively, you can use externalValue to point to an external file containing sample JSON.
examples:
singlePet:
summary: Single pet
description: A request containing a single pet
externalValue: 'https://api.example.com/docs/examples/pet.json'
Related
I am using Swagger OpenAPI Specification tool. I have a string array property in one of the definitions as follows:
cities:
type: array
items:
type: string
example: "Pune"
My API produces JSON result, so Swagger UI displays the following example for the response:
{
"cities": [
"Pune"
]
}
How can I add multiple example values for the cities array? Expecting the result as:
{
"cities": [
"Pune",
"Mumbai",
"Bangaluru"
]
}
Tried comma-separated strings in the example key like below:
cities:
type: array
items:
type: string
example: "Pune", "Mumbai", "Bangaluru"
But the Swagger Editor shows an error, "Bad indentation".
Is there any way to specify multiple values in the example key?
Update
User Helen below has given the correct answer. I had an indentation problem hence there were nested arrays (2d arrays)
Correct way:
cities:
type: array
items:
type: string
example:
- Pune
- Mumbai
My way (which was wrong)
cities:
type: array
items:
type: string
example:
- Pune
- Mumbai
Look for the indentation of the example key in the above two cases which makes the difference, its YAML indentation matters.
To display an array example with multiple items, add the example on the array level instead of item level:
cities:
type: array
items:
type: string
example:
- Pune
- Mumbai
- Bangaluru
# or
# example: [Pune, Mumbai, Bangaluru]
In case of array of objects, the example would look like this:
type: array
items:
type: object
properties:
id:
type: integer
name:
type: string
example:
- id: 1
name: Prashant
- id: 2
name: Helen
paths:
/products_1:
get:
responses:
'200':
description: "XYZ"
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/pro'
example:
- name : "Laptop"
dist : "HP LAPTOP"
- name : "Mobile"
dist : "Apple Mobile"
components:
schemas:
pro:
type: object
properties:
prodName:
type: string
example: "Laptop"
prodDesc:
type: string
example: "Produc Description"
For openapi version - 3.0.0+
major:
type: array
items:
type: string
enum:
- Accounting
- Business Contacts
- Economy
- Finance
- Graphic Design
- International Business Administration
- International Relations
- Law
- Marketing
- others
- Political Science
- Statistics
my question maybe seems to be easy, but I can't implement this on my YAML files. I would like to generate the API responses from YAML files, but I've a problem. In my JSON files, there's a key named 'type', like this:
"type": {
"id": 5,
"name": "TRONTON",
}
This key never been returned from the YAML file, because I think it's have a colliding with type parameters on YAML format itself for describing datatypes. The full code of YAML file is this:
components:
schemas:
myapi:
type: object
properties:
type:
type: object
properties:
id:
type: number
name:
type: string
Any one can help me? Thanks
I'm trying to setup an open api spec for the following snippet of JSON:
"test1": {
"1739573957": {
"tester1": 123,
"tester2": "Company"
},
"64903826718": {
"tester1": 123,
"tester2": "Company"
}
"5902849189": {
"tester1": 123,
"tester2": "Company"
}
}
The objects inside test1 have randomized guids and are listed in a way that typically would be an array, but is not. There could potentially be an infinite number of objects inside test 1. Anyone know how to set this up?
test1 is a string-to-object dictionary and can be defined as follows (assuming OpenAPI 3):
components:
schemas:
Tester: # Or however you would name the nested objects
tester1:
type: integer
example: 123
tester2:
type: string
example: Company
...
test1:
type: object
additionalProperties:
$ref: '#/components/schemas/Tester'
# Optional example for the `test1` property
example:
'1739573957':
tester1: 123
tester2: Company
'64903826718':
tester1: 123
tester2: Company
The objects inside test1 have randomized guids
In OpenAPI 3.1, you can use patternProperties instead of additionalProperties to define that the keys inside test1 are numeric strings. Earlier OpenAPI versions don't have a way to define the format of dictionary keys.
# openapi: 3.1.0
test1:
type: object
patternProperties: # <-----
'^\d+$': # <-----
$ref: '#/components/schemas/Tester'
You are looking for the free-form-object:
A free-form object (arbitrary property/value pairs) is defined as:
type: object
This is equivalent to
type: object
additionalProperties: true
and
type: object
additionalProperties: {}
However, if you can change the API, I'd highly recommend to change it to an array of tests or whatever the object defines. Put the id as property into this object and you're good to go. This makes creating DTOs for it a lot easier.
I just want to deserialise the JSON I am getting it from my server API.
For most of the solutions mentioned out there (without using any third party library), it looks like the problem is solved.
For example, the most up-voted answer on this SO thread : HERE
But the caveat which I observe is that the behaviour is not what I am expecting, when there is some extra property in json response which I am not expecting.
Let's take an example :
class Person {
id: number;
name: string;
}
let jsonString = `{
"id": 1,
"name": "sumit",
"age": 23
}`;
let person: Person = Object.assign(new Person(), JSON.parse(jsonString));
console.log(Object.keys(person));
console.log(JSON.stringify(person));
So when I work with "person" object later on, I expect that it contains only those properties which are mentioned in Person class, after all "person" is of type "Person".
But surprisingly on serializing person, it contains those extra properties which are not in Person class. Here "age"
Output for the above is :
["id", "name", "age"]
{"id":1,"name":"sumit","age":23}
Now, how do I ensure that after the Deserialization, object "person" is not having any extra properties.
If you use JSON.Parse from JSON to Person object, the prototype of the Person object is not created. Which means, if you've added a getter on the Person object, for instance, you cannot access it, because it is not available on the JSON. What you need to do create a new Person Object and map each of the properties in your JSON.
There are libraries for serializing/deserializing of JSON to Object (Person class). Checkout below library for your reference.
https://www.npmjs.com/package/#peerlancers/json-serialization
The other answers are correct. You should consider using 3-d party libraries for proper typescript class-json serialzation such as https://www.npmjs.com/package/ts-jackson
I am implementing an API-first application with the help of Swagger. One of the most important objects to be returned is a DICOM object, which returns a collection of attributes with flexible names, for example:
{
"00080005": {"vr":"CS","Value":["ISO_IR 100"]},
"00080020": {"vr":"DA","Value":["20160602"]},
"00080030": {"vr":"TM","Value":["171855.7490"]},
"00080050": {"vr":"SH","Value":["1234"]},
"00080090": {"vr":"PN","Value":[{"Alphabetic":"Parikh MD^Anush^M"}]}
}
So I cannot know the name of all the attributes in advance (00080005, 00080030, etc.) although the file structure is very uniform.
My concrete question is: what would be the schema definition for such JSON document.
I have tried the following without success:
definitions:
DicomMetadataJson:
type: object
patternProperties:
^\d{8}:
type: object
but the Swagger Editor returns an error like:
code: "OBJECT_ADDITIONAL_PROPERTIES"
message: "Additional properties not allowed: patternProperties"
description: "A deterministic version of a JSON Schema object."
OpenAPI (fka. Swagger) use only a subset of JSON Schema v4 which, unfortunately, do not propose patternProperties.
But given the provided example is a map, you can describe it using additionalProperties:
swagger: "2.0"
info:
version: 1.0.0
title: Hashmap
paths: {}
definitions:
DicomMetadataJson:
additionalProperties:
properties:
vr:
type: string
Value:
type: array
items:
type: string
The key is not defined and is supposed to be a string (therefore you cannot enforce it's format).
Note that SwaggerUI Swagger UI do not render them for now.The issue is tracked here https://github.com/swagger-api/swagger-ui/issues/1248
In the meanwhile you can use this trick define a non required property (default in the example below) of the same type of the map's objects and give some hint within the description:
swagger: "2.0"
info:
version: 1.0.0
title: Hashmap
paths: {}
definitions:
MetaData:
properties:
vr:
type: string
Value:
type: array
items:
type: string
DicomMetadataJson:
description: 'A <string,MetaData> map, default key is only for documentation purpose'
properties:
default:
$ref: '#/definitions/MetaData'
additionalProperties:
$ref: '#/definitions/MetaData'
Concerning the quote The schema exposes two types of fields. Fixed fields, which have a declared name, and Patterned fields, which declare a regex pattern for the field name. Patterned fields can have multiple occurrences as long as each has a unique name., it concerns the format of the OpenAPI specification itself and not the objects used by the API described with an OpenAPI specification.