OpenAPI – это спецификация для описания REST API. Включает набор объектов JSON с определённой схемой, которая задаёт их наименование, порядок и содержимое. Описание API по спецификации может представлять собой файл JSON, чаще – YAML.
Корневые объекты OpenAPI
openapi. В объекте указываем версию OpenAPI.
openapi: "3.0.2"
info. Объект включает заголовок, описание API, версию, ссылку на лицензию, ссылку на условия обслуживания и контактную информацию.
info:
title: "OpenWeatherMap API"
description: "Get the current weather, daily forecast for 16 days, and a three-hour-interval forecast for 5 days for your city. Helpful stats, graphics, and this day in history charts are available for your reference. Interactive maps show precipitation, clouds, pressure, wind around your location stations. Data is available in JSON, XML, or HTML format. **Note**: This sample Swagger file covers the `current` endpoint only from the OpenWeatherMap API. <br/><br/> **Note**: All parameters are optional, but you must select at least one parameter. Calling the API by city ID (using the `id` parameter) will provide the most precise location results."
version: "2.5"
termsOfService: "https://openweathermap.org/terms"
contact:
name: "OpenWeatherMap API"
url: "https://openweathermap.org/api"
email: "some_email@gmail.com"
license:
name: "CC Attribution-ShareAlike 4.0 (CC BY-SA 4.0)"
url: "https://openweathermap.org/price"
servers. В объекте указываем базовый URL, используемый в наших запросах API. Может быть указано несколько путей, к ним можно добавить description.
servers:
- url: https://api.openweathermap.org/data/2.5/
description: Production server
- url: http://beta.api.openweathermap.org/data/2.5/
description: Beta server
- url: http://some-other.api.openweathermap.org/data/2.5/
description: Some other server
paths. Объект включает endpoints и разрешённые методы. Может содержать множество подобъектов, а также ответы на запросы.
paths:
/weather:
get:
tags:
- Current Weather Data
summary: "Call current weather data for one location."
description: "Access current weather data for any location on Earth including over 200,000 cities! Current weather is frequently updated based on global models and data from more than 40,000 weather stations."
operationId: CurrentWeatherData
parameters:
- name: q
in: query
description: "**City name**. *Example: London*. You can call by city name, or by city name and country code. The API responds with a list of results that match a searching word. For the query value, type the city name and optionally the country code divided by a comma; use ISO 3166 country codes."
schema:
type: string
- name: id
in: query
description: "**City ID**. *Example: `2172797`*. You can call by city ID. The API responds with the exact result. The List of city IDs can be downloaded [here](http://bulk.openweathermap.org/sample/). You can include multiple cities in this parameter — just separate them by commas. The limit of locations is 20. *Note: A single ID counts as a one API call. So, if you have city IDs, it's treated as 3 API calls.*"
schema:
type: string
...
responses:
200:
description: Successful response
content:
application/json:
schema:
title: Sample
type: object
properties:
placeholder:
type: string
description: Placeholder description
404:
description: Not found response
content:
text/plain:
schema:
title: Weather not found
type: string
example: Not found
components. Объект для хранения переиспользуемых объектов. Переиспользование осуществляется через $ref.
paths:
/weather:
get:
tags:
- Current Weather Data
summary: "Call current weather data for one location"
description: "Access current weather data for any location on Earth including over 200,000 cities! Current weather is frequently updated based on global models and data from more than 40,000 weather stations."
operationId: CurrentWeatherData
parameters:
- $ref: '#/components/parameters/q'
- $ref: '#/components/parameters/id'
- $ref: '#/components/parameters/lat'
...
components:
parameters:
q:
name: q
in: query
description: "**City name**. *Example: London*. You can call by city name, or by city name and country code. The API responds with a list of results that match a searching word. For the query value, type the city name and optionally the country code divided by a comma; use ISO 3166 country codes."
schema:
type: string
id:
name: id
in: query
description: "**City ID**. *Example: `2172797`*. You can call by city ID. The API responds with the exact result. The List of city IDs can be downloaded [here](http://bulk.openweathermap.org/sample/). You can include multiple cities in this parameter — just separate them by commas. The limit of locations is 20. *Note: A single ID counts as a one API call. So, if you have city IDs, it's treated as 3 API calls.*"
schema:
type: string
lat:
name: lat
in: query
description: "**Latitude**. *Example: 35*. The latitude coordinate of the location of your interest. Must use with `lon`."
schema:
type: string
security. Объект указывает протокол безопасности или авторизации, используемый при отправке запросов.
security:
- app_id: []
tags. Объект группирует endpoints в Swagger UI.
tags:
- name: Current Weather Data
description: "Get current weather details"
externalDocs. Объект добавляет ссылки на внешнюю документацию.
externalDocs:
description: API Documentation
url: https://openweathermap.org/api