How can I add example for the whole struct #103
-
Hello, If I have a struct like below and i want to generate an example for the whole person struct (not each struct individual fields) how can i go about it:
The OAS output I would like to achieve is :
|
Beta Was this translation helpful? Give feedback.
Answered by
vearutop
Mar 12, 2024
Replies: 1 comment 3 replies
-
Hi, please check an example. package main
import (
"fmt"
"net/http"
"github.com/swaggest/jsonschema-go"
"github.com/swaggest/openapi-go/openapi31"
)
type p3 struct {
Name string `json:"name"`
Message string `json:"message"`
}
func (p p3) PrepareJSONSchema(schema *jsonschema.Schema) error {
// Preparer can add and example to the schema.
schema.WithExamples(p3{
Name: "itachi",
Message: "sasuki",
})
return nil
}
func main() {
reflector := openapi31.Reflector{}
reflector.Spec = &openapi31.Spec{Openapi: "3.0.3"}
reflector.Spec.Info.
WithTitle("Hello World").
WithVersion("1.2.3")
// Field examples end up as individual entries for respective properties.
type p1 struct {
Name string `json:"name" example:"itachi"`
Message string `json:"message" example:"sasuki"`
}
// Parent example in JSON format goes to whole parent schema.
type p2 struct {
Name string `json:"name"`
Message string `json:"message"`
_ struct{} `example:"{\"name\":\"itachi\",\"message\":\"sasuki\"}"` // As of github.com/swaggest/[email protected].
}
type req struct {
P1 p1 `json:"p1"`
P2 p2 `json:"p2"`
P3 p3 `json:"p3"`
}
oc, _ := reflector.NewOperationContext(http.MethodPost, "/foo")
oc.AddReqStructure(req{})
_ = reflector.AddOperation(oc)
schema, _ := reflector.Spec.MarshalYAML()
fmt.Println(string(schema))
} Result openapi: 3.0.3
info:
title: Hello World
version: 1.2.3
paths:
/foo:
post:
requestBody:
content:
application/json:
schema:
$ref: '#/components/schemas/Req'
responses:
"204":
description: No Content
components:
schemas:
P1:
properties:
message:
examples:
- sasuki
type: string
name:
examples:
- itachi
type: string
type: object
P2:
examples:
- message: sasuki
name: itachi
properties:
message:
type: string
name:
type: string
type: object
P3:
examples:
- message: sasuki
name: itachi
properties:
message:
type: string
name:
type: string
type: object
Req:
properties:
p1:
$ref: '#/components/schemas/P1'
p2:
$ref: '#/components/schemas/P2'
p3:
$ref: '#/components/schemas/P3'
type: object |
Beta Was this translation helpful? Give feedback.
3 replies
Answer selected by
vearutop
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi, please check an example.