question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Schema example generation should be straightened.

See original GitHub issue

Background

I have been working on a couple of issues and improvements related to examples of schemas. The biggest problem is that there are many components that are displaying examples in different ways. Some of them are using the util getSampleSchema(). This is a function that generates sample for a provided schema and content-type. Others just use stringify() on the examples provided for requestBody or responses.

Issues

Inconsistency in components

In my opinion all components that display samples of a schema should be using the utility getSampleSchema in order to respect the content-type.

Inconsistency in generation

While creating PR #6456 I noticed that the generation itself is inconsistent. The logic for integrating the example key of a schema into the generated sample is not the same for xml and json related content-type.

Swagger/OpenAPI definition:

openapi: 3.0.1
info:
 title: Example Swagger
 version: '1.0'
servers:
 - url: /api/v1
paths:
 /xmlTest:
   get:
     summary: sample issues
     operationId: registerSubscription
     parameters: []
     responses:
       '200':
         description: Simple example
         content:
           application/xml:
             schema:
               $ref: "#/components/schemas/Test"
           application/json:
             schema:
               $ref: "#/components/schemas/Test"
components:
 schemas:
   Test:
     type: object
     xml:
       name: root
     properties:
       x:
         type: string
       other:
         type: string
         format: email
     example: 
       x: what the f

The xml generator function sampleXmlFromSchema does:

  • Uses parent’s example of children as fallback for child schema example (Only one nesting deep)
  • Uses example value merged with sample generated from schema without example image

The json generator function sampleFromSchema instead:

  • only uses only the example value or generated schema example exclusively image

xml generator function clearly does a better job from my side. In addition I would implement example fall back to closest parent schema’s example that contains example value for current schema.

Inconsistency in handling examples

I think it would be a nice enhancement if there would be a utility that allows to parse the example value to json.

  • xml -> json
  • csv -> json

With this the getSampleSchema could also integrate literal examples within the generation process.

schema -> use content-type to gen sample json
->merge ->use content-type to stringify merged sample
raw example ->parse to json

For #6442 when using getSampleSchema there is the need to override the root schema example with content-type or media-type example. In case a property’s schema itself specifies an example, this will not lead to an override, because in case of an example defined in nested schema too it will use the nested for the sample. This is why I would like to introduce an optional parameter to getSampleSchema(..., overrideExample = undefined) this could be used to override all examples at any given nesting level. Other advantage would be not missing some example values that could be used to complete the sample.

Would like to hear some thoughts on this before I start developing.

Open Questions

  • Does the getSampleSchema fit the #6442 use case with merge and override logic? Or would it be a better approach to just parse the example value to JSON and then stringify it respectingly to the content-type or media type without merging schema sample?
  • How to display just a response or requestBody example, without taking schema into consideration, using override with merge approach?

Issue Analytics

  • State:open
  • Created 3 years ago
  • Reactions:1
  • Comments:16 (15 by maintainers)

github_iconTop GitHub Comments

2reactions
crocomcommented, Jan 20, 2021

Are there any plans to add support for yaml media type examples? Currently examples given as schema objects will render as either json or xml, but to get them to display as yaml I must copy and paste a separate example as a multi-line string.

Here is an example spec demonstrating the different behaviours:

openapi: 3.0.0
info:
  version: '0.1'
  title: Yaml vs Json Examples
  description: ''
paths:
  /resource1:
    post:
      summary: Add some resource - examples are json or xml
      operationId: myOp1
      responses:
        '201':
          description: resource created
        '400':
          description: Invalid input
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ModelA'
            examples:
              willRenderAsJson:
                $ref: '#/components/examples/example1'
          application/yaml:
            schema:
              $ref: '#/components/schemas/ModelA'
            examples:
              willRenderAsJson:
                $ref: '#/components/examples/example1'
          application/xml:
            schema:
              $ref: '#/components/schemas/ModelA'
            examples:
              willRenderAsXml:
                $ref: '#/components/examples/example1'                 
        description: Resource to add 
  /resource2:
    post:
      summary: Add some resource - examples are string or yaml
      operationId: myOp2
      responses:
        '201':
          description: resource created
        '400':
          description: Invalid input
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ModelA'
            examples:
              willRenderAsString:
                $ref: '#/components/examples/example2'
          application/yaml:
            schema:
              $ref: '#/components/schemas/ModelA'
            examples:
              willRenderAsYaml:
                $ref: '#/components/examples/example2' 
          application/xml:
            schema:
              $ref: '#/components/schemas/ModelA'
            examples:
              willRenderAsYaml:
                $ref: '#/components/examples/example2'          
        description: Resource to add         
components:
  examples:
    example1:
      summary: Example as schema object
      value:
        PropertyA: foo
        PropertyB: bar
    # to get example1 to show as YAML have to copy paste 
    # and pipe the value
    example2:
      summary: Example as literal YAML string
      value: |
        PropertyA: foo
        PropertyB: bar        
  schemas:
    ModelA:
      type: object
      properties:
        PropertyA:
          type: string
        PropertyB:
          type: string

Thanks

1reaction
mathis-mcommented, Jan 20, 2021

@tim-lai I think this would be pretty easy to integrate!

  1. Add new conditional return for yaml content-type https://github.com/swagger-api/swagger-ui/blob/ab0cdbf9d91c941977d0d8f9fe3f4cdd2318575e/src/core/utils.js#L584-L595
  2. Add getYAMLSchemaFromSample() call that wraps getStringifiedSampleForSchema():
  3. getYAMLSchemaFromSample should convert the json example result to yaml like swagger-editor does on paste:
import YAML from "js-yaml"
let yamlString
try {
  yamlString = YAML.safeDump(YAML.safeLoad(originalStr), {
    lineWidth: -1 // don't generate line folds
  })
} catch (e) {
  return
}
Read more comments on GitHub >

github_iconTop Results From Across the Web

Lecture 3: Schema Theory - Purdue Engineering
Schema. ▫ A schema is a set of binary strings that match the template for ... fixed bits, i.e. the number of bits...
Read more >
Generating New Schema Classes - Pixar Graphics
The schema generation script 'usdGenSchema' is driven by a USD layer (typically named schema.usda). Every schema.usda layer must meet the following requirements ...
Read more >
Schema generation rules · GitBook - Goswagger.Io
So that after generation you should be able to reverse-generate a spec from the code that was generated by your spec. It should...
Read more >
Generating Schemas from Examples with jtd-infer
jtd-infer is a tool that can generate a JSON Typedef schema from example data. ... to think about than diving straight into writing...
Read more >
Inheritance and Polymorphism - Swagger
In the example above, the ExtendedErrorModel schema includes its own properties and ... One possible example are code generation tools: they can use ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found