1. Introduction
In this tutorial, we’ll see how to declare dates in an OpenAPI file, in this case, implemented with Swagger. This will allow us to manage input and output dates in a standardized way when calling external APIs.
2. Swagger vs. OAS
Swagger is a set of tools implementing the OpenAPI Specification (OAS), a language-agnostic interface to document RESTful APIs. This allows us to understand the capabilities of any service without accessing the source code.
To implement this, we’ll have a file in our project, typically YAML or JSON, describing APIs using OAS. We’ll then use Swagger tools to:
- edit our specification through a browser (Swagger Editor)
- auto-generate API client libraries (Swagger Codegen)
- show auto-generated documentation (Swagger UI)
The OpenAPI file example contains different sections, but we’ll focus on the model definition.
3. Defining a Date
Let’s define a User entity using the OAS:
components:
User:
type: "object"
properties:
id:
type: integer
format: int64
createdAt:
type: string
format: date
description: Creation date
example: "2021-01-30"
username:
type: string
To define a date, we use an object with:
- the type field equals to string
- the format field which specifies how the date is formed
In this case, we used the date format to describe the createdAt date. This format describes dates using the ISO 8601 full-date format.
4. Defining a Date-Time
Additionally, if we also want to specify the time, we’ll use date-time as the format. Let’s see an example:
createdAt:
type: string
format: date-time
description: Creation date and time
example: "2021-01-30T08:30:00Z"
In this case, we’re describing date-times using the ISO 8601 full-time format.
5. The pattern field
Using OAS, we can describe dates with other formats as well. To do so, let’s use the pattern field:
customDate:
type: string
pattern: '^\d{4}(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])$'
description: Custom date
example: "20210130"
Clearly, this is the less readable method, but the most powerful. Indeed, we can use any regular expression in this field.
6. Conclusion
In this article, we’ve seen how to declare dates using OpenAPI. We can use standard formats offered by OpenAPI as well as custom patterns to match our needs. As always, the source code of the example we used is available over on GitHub.
The post Dates in OpenAPI Files first appeared on Baeldung.
Find A Teacher Form:
https://docs.google.com/forms/d/1vREBnX5n262umf4wU5U2pyTwvk9O-JrAgblA-wH9GFQ/viewform?edit_requested=true#responses
Email:
public1989two@gmail.com
www.itsec.hk
www.itsec.vip
www.itseceu.uk
Leave a Reply