Skip to main content

Correct way to declare a date in an OpenAPI

· 2 min read
Serhii Hrekov
software engineer, creator, artist, programmer, projects founder

In OpenAPI, the correct way to declare a date is by using the string type along with a specific format. The format distinguishes a date from a regular string and provides a standard for validation and code generation.

Correct Declaration

The OpenAPI specification defines several standard formats for date and time values. For a date (without time), you should use format: date.

type: string
format: date

For a date-time value, you should use format: date-time.

type: string
format: date-time

These formats align with ISO 8601 standards (1), which are the globally recognized standard for representing dates and times.

Example Usage

Here's how you'd use these in a schema within your OpenAPI specification:

openapi: 3.0.0
info:
title: My API
version: 1.0.0
paths: {}
components:
schemas:
Event:
type: object
properties:
eventDate:
type: string
format: date
description: The date of the event in YYYY-MM-DD format.
eventDateTime:
type: string
format: date-time
description: The date and time of the event in ISO 8601 format.

In summary, always use type: string with format: date or format: date-time to ensure your date and time fields are correctly interpreted by tooling and understood by other developers.

Sources

  1. OpenAPI Specification: Formats
  2. Understanding JSON Schema: Formats