Reputation: 1775
I'm defining the following in swagger 2.0 "definition" section. I first defined the format of timestamp that I would use in many object's properties for different purposes, such as created timestamp and last updated timestamp.
definitions:
TimeStamp:
title: Timestamp format
description: ISO 8681, "2016-08-18T17:33:00Z"
type: string
pattern: \d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z
Application:
title: An application
type: object
properties:
cDtm:
title: Creation timestamp
description: Some description
type: string
pattern:\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z
However, when defining the "cDtm" property of the "Application" object, I cannot find a way to reuse the timestamp definition. If I use "$ref" along with "title" and "description", I get a warning "sibling values are not allowed alongside '$ref'". If I don't use "$ref", I need to repeat the type and pattern definition as above.
So, my question is, is there a way to use $ref to reuse a string pattern definition but still able to give the defined property a new title and description?
Thanks!
Bing
Upvotes: 3
Views: 6137
Reputation: 96
openapi: 3.0.0
info:
title: A dummy title
version: 1.0.0
paths:
/post:
post:
requestBody:
content:
application/json:
schema:
type: object
required:
- msisdn
- network
properties:
msisdn:
title: "msidn"
description: "msidn"
allOf:
- $ref: "#/components/schemas/msisdn-regex"
msisdn1:
title: "msidn1"
description: "msidn1"
allOf:
- $ref: "#/components/schemas/msisdn-regex"
msisdn2:
title: "msidn2"
description: "msidn2"
allOf:
- $ref: "#/components/schemas/msisdn-regex"
IMEI:
type: integer
Network:
type: string
example: # Sample object
msisdn: "10"
IMEI: 20
Network:
- Vodafone
- Jio
- Airtel
required: true
responses:
'200':
description: OK
servers:
- url: http://httpbin.org
components:
schemas:
msisdn-regex:
type: string
pattern: ^[0-9]{10}$
example: "1234567897"
Upvotes: 0
Reputation: 97589
OpenAPI Specification includes built-in format: date-time
for this format, so you don't actually need a pattern
here. Instead, use:
type: string
format: date-time
If, for some reason, you want to stick with the pattern
, you can use the following workaround. Basically, you can "add" properties to a $ref
if you wrap the $ref
into allOf
. This works in Swagger Editor and Swagger UI, but other tooling support may vary.
Application:
title: An application
type: object
properties:
cDtm:
title: Creation timestamp
description: Some description
allOf:
- $ref: '#/definitions/TimeStamp'
Also keep in mind that pattern
works as a partial match by default. To force an exact match, enclose the pattern expression into ^..$
:
pattern: ^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$
Upvotes: 6