Reputation: 10843
Say I have an OpenAPI swagger.yml
file that looks like:
openapi: '3.0.2'
info:
title: Simplest ever
version: '1.0'
servers:
- url: https://api.server.test/v1
paths:
/test:
get:
responses:
'200':
description: OK
content:
application/json:
schema:
type: object
properties:
message:
type: string
I prefer to keep the source of truth schema in my schemas/ directory, for example schemas/get.json
looks like:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"message": {
"type": "string"
}
}
}
The intent is for the schemas/*.json to used in my backend code base for validation for incoming and outgoing messages. Goal is to have strong API contracts.
What I don't understand is how to build the swagger.yml
file using these JSON schema, instead of duplicating the work in YAML which is really tedious and error prone.
Upvotes: 12
Views: 14983
Reputation: 97982
In OpenAPI 3.1, you can reference your JSON Schemas directly:
# openapi: 3.1.0
content:
application/json:
schema:
$ref: 'schemas/get.json'
Earlier OpenAPI versions expect that the JSON Schemas be converted to the OpenAPI Schema Object format (which can be represented as both YAML and JSON). The necessary changes include, for example:
$schema
, patternProperties
, and others;type: [<foo>, 'null']
with type: <foo>
+ nullable: true
;type: [type1, type2, ...]
with oneOf
/anyOf
(OAS3) or removing them (OAS2).json-schema-to-openapi-schema
can automate the conversion.
You can try to $ref
vanilla JSON Schemas directly from OAS 2.0 and 3.0 definitions, but some tools will error out on unexpected keywords and constructs.
Upvotes: 18