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:
description: Creation date
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:
description: Creation date and time
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:
description: Custom date
Clearly, this is the less readable method, but the most powerful. Indeed, we can use any regular expression in this field.
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.
res – REST with Spring (eBook) (everywhere)