### Setting up Swagger Editor Repository
Source: https://swagger.io/docs/open-source-tools/swagger-editor-next
Commands to clone the Swagger Editor repository, checkout the 'next' branch, initialize and update submodules, install dependencies, and start the development server.
```bash
git clone https://github.com/swagger-api/swagger-editor.git
cd swagger-editor
git checkout next
git submodule init
git submodule update
npm i
npm start
```
--------------------------------
### Parameter Examples
Source: https://swagger.io/docs/specification/adding-examples
Demonstrates how to specify a single example value for an API parameter.
```APIDOC
## GET /api/resource
### Description
This endpoint retrieves resources with an optional status filter.
### Method
GET
### Endpoint
/api/resource
### Parameters
#### Query Parameters
- **status** (string) - Optional - Filters resources by their status. Allowed values: approved, pending, closed, new.
### Request Example
```
GET /api/resource?status=approved
```
### Response
#### Success Response (200)
- **data** (array) - A list of resources.
- **status** (string) - The status of the resource.
#### Response Example
```json
{
"data": [
{
"id": 1,
"name": "Example Resource",
"status": "approved"
}
]
}
```
```
--------------------------------
### Response Body Multiple Examples (Media Type Child with $ref)
Source: https://swagger.io/docs/specification/adding-examples
Shows how to provide multiple examples for a response body when using a $ref for the schema. The 'examples' keyword is used under the media type, with each example having a 'value' property.
```yaml
responses:
"200":
description: A user object.
content:
application/json:
schema:
$ref: "#/components/schemas/User" # Reference to an object
examples:
Jessica:
value:
id: 10
name: Jessica Smith
Ron:
value:
id: 20
name: Ron Stewart
```
--------------------------------
### Multiple Parameter Examples
Source: https://swagger.io/docs/specification/adding-examples
Illustrates how to provide multiple named examples for a single API parameter, including optional summaries.
```APIDOC
## GET /api/items
### Description
This endpoint retrieves a list of items, with an optional limit parameter.
### Method
GET
### Endpoint
/api/items
### Parameters
#### Query Parameters
- **limit** (integer) - Optional - The maximum number of items to return. Maximum value: 50.
### Request Example
```
GET /api/items?limit=50
```
### Response
#### Success Response (200)
- **items** (array) - A list of items.
- **count** (integer) - The number of items returned.
#### Response Example
```json
{
"items": [
{
"id": 1,
"name": "Item 1"
},
{
"id": 2,
"name": "Item 2"
}
],
"count": 2
}
```
```
--------------------------------
### Array Examples
Source: https://swagger.io/docs/specification/adding-examples
Illustrates how to provide examples for arrays, including arrays of integers and arrays of objects.
```APIDOC
## Components Schemas - Array Examples
### Description
This section shows how to define examples for array types in OpenAPI specifications.
### Components
#### Schemas
##### ArrayOfInt (Array of Integers)
- **type**: array
- **items**:
- **type**: integer
- **format**: int64
- **example**: 1
### Array-level Example (Integers)
```json
[1, 2, 3]
```
##### ArrayOfUsers (Array of Objects)
- **type**: array
- **items**:
- **type**: object
- **properties**:
- **id** (integer)
- **name** (string)
### Array-level Example (Objects)
```json
[
{
"id": 10,
"name": "Jessica Smith"
},
{
"id": 20,
"name": "Ron Stewart"
}
]
```
```
--------------------------------
### POST /users - Add New User
Source: https://swagger.io/docs/specification/adding-examples
This endpoint allows for the addition of a new user. It demonstrates how to define request body examples, including single examples and multiple examples using the 'examples' keyword.
```APIDOC
## POST /users
### Description
Adds a new user to the system.
### Method
POST
### Endpoint
/users
### Parameters
#### Request Body
- **id** (integer) - Required - The unique identifier for the user.
- **name** (string) - Required - The name of the user.
### Request Example
```json
{
"id": 10,
"name": "Jessica Smith"
}
```
### Response
#### Success Response (200)
- **description** (string) - Indicates that the request was successful.
#### Response Example
```json
{
"message": "User added successfully"
}
```
```
--------------------------------
### Response Body Example (Media Type Child with $ref)
Source: https://swagger.io/docs/specification/adding-examples
Demonstrates using the 'example' keyword for a response body when the schema is a reference ($ref). The example is placed under the media type.
```yaml
responses:
"200":
description: A user object.
content:
application/json:
schema:
$ref: "#/components/schemas/User" # Reference to an object
example:
# Properties of the referenced object
id: 10
name: Jessica Smith
```
--------------------------------
### Complete OpenAPI Example with Links
Source: https://swagger.io/docs/specification/links
A full OpenAPI 3.0.4 example showcasing the 'links' feature. It defines a 'createUser' POST operation and a 'getUser' GET operation, with a link from the 'createUser' response to 'getUser' using the created user's ID.
```yaml
openapi: 3.0.4
info:
version: 0.0.0
title: Links example
paths:
/users:
post:
summary: Creates a user and returns the user ID
operationId: createUser
requestBody:
required: true
description: A JSON object that contains the user name and age.
content:
application/json:
schema:
$ref: "#/components/schemas/User"
responses:
"201":
description: Created
content:
application/json:
schema:
type: object
properties:
id:
type: integer
format: int64
description: ID of the created user.
# -----------------------------------------------------
# Links
# -----------------------------------------------------
links:
GetUserByUserId: # <---- arbitrary name for the link
operationId: getUser
# or
# operationRef: '#/paths/~1users~1{userId}/get'
parameters:
userId: "$response.body#/id"
description: >
The `id` value returned in the response can be used as
the `userId` parameter in `GET /users/{userId}`.
# -----------------------------------------------------
/users/{userId}:
get:
summary: Gets a user by ID
operationId: getUser
parameters:
- in: path
name: userId
required: true
schema:
type: integer
format: int64
responses:
"200":
description: A User object
content:
application/json:
schema:
$ref: "#/components/schemas/User"
components:
schemas:
User:
type: object
properties:
id:
type: integer
format: int64
readOnly: true
name:
type: string
```
--------------------------------
### Add Multiple Examples to OpenAPI Parameter (YAML)
Source: https://swagger.io/docs/specification/adding-examples
This snippet shows how to specify multiple examples for a single OpenAPI parameter using the `examples` key. Each example is given a distinct key name and can optionally include a `summary` for a brief description. This feature, supported in Swagger UI 3.23.0+ and Swagger Editor 3.6.31+, allows for richer parameter illustration.
```yaml
parameters:
- in: query
name: limit
schema:
type: integer
maximum: 50
examples:
zero:
value: 0
summary: A sample limit value
max:
value: 50
summary: A sample limit value
```
--------------------------------
### Request Body Multiple Examples (Media Type Child with $ref)
Source: https://swagger.io/docs/specification/adding-examples
Illustrates providing multiple examples for a request body when using a $ref for the schema. The 'examples' keyword is used, with each example having a 'value' property.
```yaml
paths:
/users:
post:
summary: Adds a new user
requestBody:
content:
application/json: # Media type
schema: # Request body contents
$ref: "#/components/schemas/User" # Reference to an object
examples: # Child of media type
Jessica: # Example 1
value:
id: 10
name: Jessica Smith
Ron: # Example 2
value:
id: 11
name: Ron Stewart
responses:
"200":
description: OK
```
--------------------------------
### Examples for XML and HTML Data
Source: https://swagger.io/docs/specification/adding-examples
Demonstrates how to specify inline examples for XML and HTML content types when they cannot be represented in JSON or YAML.
```APIDOC
## Examples for XML and HTML Data
### Description
To describe an example value that cannot be presented in JSON or YAML format, specify it as a string.
### Method
N/A (This describes a specification structure, not an endpoint)
### Endpoint
N/A
### Parameters
N/A
### Request Example
```yaml
content:
application/xml:
schema:
$ref: "#/components/schemas/xml"
examples:
xml:
summary: A sample XML response
value: ""
text/html:
schema:
type: string
examples:
html:
summary: A list containing two items
value: "
item 1
item 2
"
```
### Response
N/A
### Response Example
N/A
```
--------------------------------
### Request Body Example (Media Type Child with $ref)
Source: https://swagger.io/docs/specification/adding-examples
Shows how to use the 'example' keyword as a child of the media type when the schema is a reference ($ref). This is necessary because $ref overwrites sibling keywords.
```yaml
paths:
/users:
post:
summary: Adds a new user
requestBody:
content:
application/json: # Media type
schema: # Request body contents
$ref: "#/components/schemas/User" # Reference to an object
example: # Child of media type because we use $ref above
# Properties of a referenced object
id: 10
name: Jessica Smith
responses:
"200":
description: OK
```
--------------------------------
### User Object Schema Examples
Source: https://swagger.io/docs/specification/adding-examples
Demonstrates how to provide examples for object schemas and individual properties within the components section of an OpenAPI specification.
```APIDOC
## Components Schemas - User Object Examples
### Description
This section details how to define examples for the 'User' object schema and its properties.
### Components
#### Schemas
##### User (Object Schema)
- **type**: object
- **properties**:
- **id** (integer) - The unique identifier for the user. `example`: 1
- **name** (string) - The name of the user. `example`: New order
### Object-level Example
```json
{
"id": 1,
"name": "Jessica Smith"
}
```
### Property-level Examples
- **id**: `1`
- **name**: `New order`
```
--------------------------------
### Component Schema Object Example
Source: https://swagger.io/docs/specification/adding-examples
Demonstrates providing an example for an entire object schema in the 'components' section. This shows a complete instance of the object being defined.
```yaml
components:
schemas:
User: # Schema name
type: object
properties:
id:
type: integer
name:
type: string
example: # Object-level example
id: 1
name: Jessica Smith
```
--------------------------------
### Reusing Examples
Source: https://swagger.io/docs/specification/adding-examples
Explains how to define common examples in the `components/examples` section and reuse them across different parts of the API specification.
```APIDOC
## Reusing Examples
### Description
You can define common examples in the `components/examples` section of your specification and then re-use them in various parameter descriptions, request and response body descriptions, objects and properties.
### Method
N/A (This describes a specification structure, not an endpoint)
### Endpoint
N/A
### Parameters
N/A
### Request Example
```yaml
content:
application/json:
schema:
$ref: '#/components/schemas/MyObject'
examples:
objectExample:
$ref: '#/components/examples/objectExample'
...
components:
examples:
objectExample:
value:
id: 1
name: new object
summary: A sample object
```
### Response
N/A
### Response Example
N/A
```
--------------------------------
### Detailed OpenAPI Operation with Parameters and Schema
Source: https://swagger.io/docs/specification/paths-and-operations
A comprehensive example of an OpenAPI operation for 'GET /users/{id}'. It includes tags, summary, description, operationId, path parameters, and a response schema referencing a User component.
```yaml
paths:
/users/{id}:
get:
tags:
- Users
summary: Gets a user by ID.
description: |
A detailed description of the operation.
Use markdown for rich text representation,
such as **bold**, *italic*, and [links](https://swagger.io).
operationId: getUserById
parameters:
- name: id
in: path
description: User ID
required: true
schema:
type: integer
format: int64
responses:
"200":
description: Successful operation
content:
application/json:
schema:
$ref: "#/components/schemas/User"
externalDocs:
description: Learn more about user operations provided by this API.
url: http://api.example.com/docs/user-operations/
components:
schemas:
User:
type: object
properties:
id:
type: integer
format: int64
name:
type: string
required:
- id
- name
```
--------------------------------
### Parameter Examples
Source: https://swagger.io/docs/specification/describing-parameters
Illustrates how to provide single or multiple named examples for parameters to clarify their usage.
```APIDOC
## Single Parameter Example
### Description
Specifies a single example value for a parameter that matches its schema.
### Parameters
#### Query Parameters
- **limit** (integer) - Optional - The maximum number of items to return.
- `minimum: 1`
- `example: 20`
## Multiple Named Parameter Examples
### Description
Provides multiple, distinctly named examples for a parameter, useful for array types or complex scenarios.
### Parameters
#### Query Parameters
- **ids** (array[integer]) - Required - One or more IDs.
- `style: form`
- `explode: false`
- `examples`:
- **oneId**:
- `summary: Example of a single ID`
- `value: [5]`
- **multipleIds**:
- `summary: Example of multiple IDs`
- `value: [1, 5, 7]`
### Request Example (for multipleIds)
```
GET /resource?ids=1,5,7
```
```
--------------------------------
### Inline XML and HTML Examples in Swagger/OpenAPI
Source: https://swagger.io/docs/specification/adding-examples
Demonstrates how to provide inline examples for XML and HTML content within a Swagger/OpenAPI specification. This is useful when the example data cannot be represented in standard JSON or YAML formats. The 'value' keyword holds the literal example string.
```yaml
content:
application/xml:
schema:
$ref: "#/components/schemas/xml"
examples:
xml:
summary: A sample XML response
value: ""
text/html:
schema:
type: string
examples:
html:
summary: A list containing two items
value: "
item 1
item 2
"
```
--------------------------------
### Embed Swagger UI Standalone Preset HTML with unpkg
Source: https://swagger.io/docs/open-source-tools/swagger-ui/usage/installation
This example demonstrates embedding Swagger UI with the StandalonePreset using unpkg. It includes the necessary HTML, CSS, and JavaScript, along with the `swagger-ui-standalone-preset.js` script. This preset enables features like TopBar and ValidatorBadge, offering a more complete UI experience.
```html
SwaggerUI
```
--------------------------------
### Example: Paginated Item Retrieval (HTTP Request)
Source: https://swagger.io/docs/specification/links
This snippet illustrates an HTTP GET request for retrieving a list of items with a specified limit. It shows how a cursor parameter can be used in subsequent requests to fetch the next set of data, demonstrating pagination.
```http
GET /items?limit=100
```
--------------------------------
### Component Schema Array Item Example
Source: https://swagger.io/docs/specification/adding-examples
Shows how to specify an example for an individual item within an array schema in the 'components' section. This is useful for documenting the structure of elements within the array.
```yaml
components:
schemas:
ArrayOfInt:
type: array
items:
type: integer
format: int64
example: 1
```
--------------------------------
### Importing Individual Swagger Editor Presets
Source: https://swagger.io/docs/open-source-tools/swagger-editor-next
Shows how to import presets, which are collections of plugins designed to work together. Presets simplify the setup by providing pre-configured feature sets. Examples include 'textarea' and 'monaco' presets.
```javascript
import TextareaPreset from 'swagger-editor/presets/textarea';
import MonacoPreset from 'swagger-editor/presets/monaco';
```
--------------------------------
### Component Schema Array Example (Multiple Items)
Source: https://swagger.io/docs/specification/adding-examples
Illustrates providing an example for an entire array, containing multiple items, within a schema in the 'components' section. This provides a sample of the array's content.
```yaml
components:
schemas:
ArrayOfInt:
type: array
items:
type: integer
format: int64
example: [1, 2, 3]
```
--------------------------------
### Install Node.js Dependencies for Swagger UI
Source: https://swagger.io/docs/open-source-tools/swagger-ui/development/setting-up
After cloning the repository, navigate into the directory and run this command to install all necessary Node.js dependencies. Requires Node.js and npm to be installed.
```bash
cd swagger-ui
npm install
```
--------------------------------
### Request Body Example (Schema Child)
Source: https://swagger.io/docs/specification/adding-examples
Demonstrates using the 'example' keyword as a child of 'schema' for a request body. This is suitable when the schema is defined inline.
```yaml
paths:
/users:
post:
summary: Adds a new user
requestBody:
content:
application/json:
schema: # Request body contents
type: object
properties:
id:
type: integer
name:
type: string
example: # Sample object
id: 10
name: Jessica Smith
responses:
"200":
description: OK
```
--------------------------------
### Reusing Defined Examples in Swagger/OpenAPI
Source: https://swagger.io/docs/specification/adding-examples
Illustrates how to define common examples in the `components/examples` section and then reuse them across different parts of the Swagger/OpenAPI specification using the '$ref' keyword. This promotes consistency and reduces redundancy.
```yaml
content:
application/json:
schema:
$ref: '#/components/schemas/MyObject'
examples:
objectExample:
$ref: '#/components/examples/objectExample'
...
components:
examples:
objectExample:
value:
id: 1
name: new object
summary: A sample object
```
--------------------------------
### Define Multiple Request Body Examples (YAML)
Source: https://swagger.io/docs/specification/describing-request-body/describing-request-body
This snippet shows how to define multiple examples for a request body using the 'examples' property. It illustrates inline examples with summaries, external referenced examples via 'externalValue', and examples referenced from the 'components.examples' section using '$ref'.
```yaml
requestBody:
content:
application/json:
schema:
$ref: '#/components/schemas/Pet'
examples:
dog:
summary: An example of a dog
value:
name: Fluffy
petType: dog
cat:
summary: An example of a cat
externalValue: http://api.example.com/examples/cat.json
hamster:
$ref: '#/components/examples/hamster'
components:
examples:
hamster:
summary: An example of a hamster
value:
name: Ginger
petType: hamster
```
--------------------------------
### Add Single Example to OpenAPI Parameter (YAML)
Source: https://swagger.io/docs/specification/adding-examples
This snippet demonstrates how to add a single example value to an OpenAPI parameter using the `example` key. It's useful for providing a clear, representative value for a parameter, aiding tools like API mockers. The example value must match the parameter's schema type.
```yaml
parameters:
- in: query
name: status
schema:
type: string
enum: [approved, pending, closed, new]
example: approved
```
--------------------------------
### Component Schema Property Example
Source: https://swagger.io/docs/specification/adding-examples
Illustrates defining an example for an individual property within a schema in the 'components' section. This helps document the expected format or value of a specific field.
```yaml
components:
schemas:
User: # Schema name
type: object
properties:
id:
type: integer
format: int64
example: 1 # Property example
name:
type: string
example: New order # Property example
```
--------------------------------
### External Examples
Source: https://swagger.io/docs/specification/adding-examples
Shows how to use the `externalValue` keyword to reference example values from external URLs when they cannot be directly embedded in the specification.
```APIDOC
## External Examples
### Description
If a sample value cannot be inserted into your specification for some reason, for instance, it is neither YAML-, nor JSON-conformant, you can use the `externalValue` keyword to specify the URL of the example value. The URL should point to the resource that contains the literal example contents (an object, file or image, for example).
### Method
N/A (This describes a specification structure, not an endpoint)
### Endpoint
N/A
### Parameters
N/A
### Request Example
```yaml
content:
application/json:
schema:
$ref: "#/components/schemas/MyObject"
examples:
jsonObject:
summary: A sample object
externalValue: "http://example.com/examples/object-example.json"
application/pdf:
schema:
type: string
format: binary
examples:
sampleFile:
summary: A sample file
externalValue: "http://example.com/examples/example.pdf"
```
### Response
N/A
### Response Example
N/A
```
--------------------------------
### Component Schema Array of Objects Example
Source: https://swagger.io/docs/specification/adding-examples
Demonstrates providing a multi-item example for an array of objects within a schema in the 'components' section. This shows a sample array containing multiple object instances.
```yaml
components:
schemas:
ArrayOfUsers:
type: array
items:
type: object
properties:
id:
type: integer
name:
type: string
example:
- id: 10
name: Jessica Smith
- id: 20
name: Ron Stewart
```
--------------------------------
### Define Multiple Named Examples for Array Parameter (YAML)
Source: https://swagger.io/docs/specification/describing-parameters
This snippet demonstrates defining multiple, named examples for an array-type query parameter. The `examples` object contains key-value pairs, where each key is a name for the example (e.g., `oneId`, `multipleIds`), and the value provides a `summary` and the actual `value` for the example. This is useful for showcasing different valid inputs for complex parameters.
```yaml
parameters:
- in: query
name: ids
description: One or more IDs
required: true
schema:
type: array
items:
type: integer
style: form
explode: false
examples:
oneId:
summary: Example of a single ID
value: [5] # ?ids=5
multipleIds:
summary: Example of multiple IDs
value: [1, 5, 7] # ?ids=1,5,7
```
--------------------------------
### External Examples for JSON and PDF in Swagger/OpenAPI
Source: https://swagger.io/docs/specification/adding-examples
Shows how to reference external example values using the 'externalValue' keyword for content types like JSON and PDF. This is beneficial when the example is too large or complex to embed directly, or when it resides in a separate file. The URL should point to the resource containing the example.
```yaml
content:
application/json:
schema:
$ref: "#/components/schemas/MyObject"
examples:
jsonObject:
summary: A sample object
externalValue: "http://example.com/examples/object-example.json"
application/pdf:
schema:
type: string
format: binary
examples:
sampleFile:
summary: A sample file
externalValue: "http://example.com/examples/example.pdf"
```
--------------------------------
### Server Templating Examples
Source: https://swagger.io/docs/specification/api-host-and-base-path
Provides various examples of server templating for different use cases.
```APIDOC
## Server Templating Examples
### Description
Illustrates common use cases for server templating.
#### HTTPS and HTTP
```yaml
servers:
- url: http://api.example.com
- url: https://api.example.com
```
Or using templating:
```yaml
servers:
- url: '{protocol}://api.example.com'
variables:
protocol:
enum:
- http
- https
default: https
```
#### Production, Development, and Staging
```yaml
servers:
- url: https://{environment}.example.com/v2
variables:
environment:
default: api # Production server
enum:
- api # Production server
- api.dev # Development server
- api.staging # Staging server
```
#### SaaS and On-Premise
```yaml
servers:
- url: "{server}/v1"
variables:
server:
default: https://api.example.com # SaaS server
```
#### Regional Endpoints
```yaml
servers:
- url: https://{region}.api.cognitive.microsoft.com
variables:
region:
default: westus
enum:
- westus
- eastus2
- westcentralus
- westeurope
- southeastasia
```
```
--------------------------------
### Example Query Parameter Usage
Source: https://swagger.io/docs/specification/describing-parameters
Provides examples of API endpoints utilizing query parameters. The first example shows filtering by 'status', while the second demonstrates pagination using 'offset' and 'limit'. These illustrate common use cases for query parameters.
```text
GET /pets/findByStatus?status=available
GET /notes?offset=100&limit=50
```
--------------------------------
### Install Swagger Editor via npm
Source: https://swagger.io/docs/open-source-tools/swagger-editor-next
This command demonstrates how to install the Swagger Editor npm package, specifically the alpha version. Ensure you have Node.js and the necessary prerequisites installed before running this command.
```bash
$ npm install swagger-editor@alpha
```
--------------------------------
### Define Single Example for Query Parameter (YAML)
Source: https://swagger.io/docs/specification/describing-parameters
This YAML code illustrates how to specify a single example value for a query parameter. The `example` property is used, and its value must conform to the parameter's schema. This helps in understanding and testing the expected input for the parameter.
```yaml
parameters:
- in: query
name: limit
schema:
type: integer
minimum: 1
example: 20
```
--------------------------------
### Docker Environment Variable - String Example
Source: https://swagger.io/docs/open-source-tools/swagger-ui/usage/configuration
Example of setting string environment variables for Dockerized Swagger UI.
```bash
FILTER="myFilterValue"
LAYOUT="BaseLayout"
```
--------------------------------
### Docker Environment Variable - Number Example
Source: https://swagger.io/docs/open-source-tools/swagger-ui/usage/configuration
Example of setting number environment variables for Dockerized Swagger UI.
```bash
DEFAULT_MODELS_EXPAND_DEPTH="5"
DEFAULT_MODEL_EXPAND_DEPTH="7"
```
--------------------------------
### Install Swagger UI Packages via NPM
Source: https://swagger.io/docs/open-source-tools/swagger-ui/usage/installation
Installs the core `swagger-ui`, `swagger-ui-react`, and `swagger-ui-dist` packages from the NPM registry. These packages provide the necessary files for integrating Swagger UI into web applications.
```bash
npm install swagger-ui
```
```bash
npm install swagger-ui-react
```
```bash
npm install swagger-ui-dist
```
--------------------------------
### GET /users
Source: https://swagger.io/docs/specification/basic-structure
Retrieves a list of users. The response contains a JSON array of user names.
```APIDOC
## GET /users
### Description
Returns a list of users. The response contains a JSON array of user names.
### Method
GET
### Endpoint
/users
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
None
### Response
#### Success Response (200)
- **Array of Strings** - A JSON array of user names
#### Response Example
{
"example": "[\"user1\", \"user2\"]"
}
```
--------------------------------
### Docker Environment Variable - Array Example
Source: https://swagger.io/docs/open-source-tools/swagger-ui/usage/configuration
Example of setting array environment variables for Dockerized Swagger UI. Ensure proper escaping of characters within the array string.
```bash
SUPPORTED_SUBMIT_METHODS="[\"get\", \"post\"]"
URLS="[ { url: \"https://petstore.swagger.io/v2/swagger.json\", name: \"Petstore\" } ]"
```
--------------------------------
### API Path and Operation Definition (GET /users)
Source: https://swagger.io/docs/specification/basic-structure
Defines an API endpoint, specifically the 'GET' operation for the '/users' path. It includes a summary, extended description, and details about the expected '200' OK response, including the JSON schema for the response body.
```yaml
paths:
/users:
get:
summary: Returns a list of users.
description: Optional extended description in CommonMark or HTML
responses:
"200":
description: A JSON array of user names
content:
application/json:
schema:
type: array
items:
type: string
```
--------------------------------
### Minimal OpenAPI Operation Definition
Source: https://swagger.io/docs/specification/paths-and-operations
A basic example of an OpenAPI operation defining a 'get' method for the '/ping' path, including a simple '200' response with a description.
```yaml
paths:
/ping:
get:
responses:
"200":
description: OK
```
--------------------------------
### Define Header Parameter in OpenAPI
Source: https://swagger.io/docs/specification/describing-parameters
Shows how to define a custom request header parameter using `in: header`. This example defines an `X-Request-ID` header for a `GET /ping` operation.
```yaml
paths:
/ping:
get:
summary: Checks if the server is alive
parameters:
- in: header
name: X-Request-ID
schema:
type: string
format: uuid
required: true
```
--------------------------------
### Get Components in JavaScript
Source: https://swagger.io/docs/open-source-tools/swagger-ui/customization/plugin-api
This example demonstrates how to retrieve registered components from the system using the `getComponent` method. This allows you to use components defined elsewhere in your plugin or in the core Swagger UI.
```javascript
// elsewhere
const HelloWorldStateless = system.getComponent("HelloWorldStateless")
const HelloWorldClass = system.getComponent("HelloWorldClass")
```
--------------------------------
### GET /items with Enum Query Parameter
Source: https://swagger.io/docs/specification/data-models/enums
This example demonstrates how to define a query parameter with an enum using OpenAPI 3.0 syntax. The 'sort' parameter accepts either 'asc' or 'desc'.
```APIDOC
## GET /items
### Description
Retrieves a list of items, with an option to specify the sort order.
### Method
GET
### Endpoint
/items
### Parameters
#### Query Parameters
- **sort** (string) - Optional - Sort order. Accepts 'asc' or 'desc'.
### Request Example
```json
{
"example": "GET /items?sort=asc"
}
```
### Response
#### Success Response (200)
- **items** (array) - A list of items.
#### Response Example
```json
{
"example": {
"items": [
{ "id": 1, "name": "Item 1" },
{ "id": 2, "name": "Item 2" }
]
}
}
```
```
--------------------------------
### Build-Free SwaggerUI with Preview Plugins via unpkg.com (HTML/JavaScript)
Source: https://swagger.io/docs/open-source-tools/swagger-editor-next
This HTML and JavaScript example shows how to use SwaggerUI with preview plugins for AsyncAPI and API Design Systems without a build process, leveraging unpkg.com. It includes necessary CSS and JS files from CDNs and configures SwaggerUIBundle with the relevant editor plugins.
```html
```
--------------------------------
### Docker Compose Environment Variables (.env file) (Shell)
Source: https://swagger.io/docs/open-source-tools/swagger-ui/usage/configuration
Provides examples of environment variable configurations for a Docker Compose setup, specifically for the swagger.io project. It shows how to define supported submission methods and a list of URLs with associated names.
```shell
SUPPORTED_SUBMIT_METHODS=['get', 'post']
URLS=[ { url: 'https://petstore.swagger.io/v2/swagger.json', name: 'Petstore' } ]
```
--------------------------------
### Dictionary Example with Sample Content
Source: https://swagger.io/docs/specification/data-models/dictionaries
This schema defines a string-to-string dictionary and provides sample content using the `example` keyword. The sample shows key-value pairs for English and French greetings.
```yaml
type: object
additionalProperties:
type: string
example:
en: Hello!
fr: Bonjour!
```
--------------------------------
### Get Language-Specific Swagger Codegen Options (CLI)
Source: https://swagger.io/docs/open-source-tools/swagger-codegen/codegen-v3/about
This command retrieves a list of options specific to a particular language generator within Swagger Codegen. For example, running `config-help -l php` will show options relevant only to PHP client generation.
```shell
java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar config-help -l php
```
--------------------------------
### OpenAPI 3.0.4 Basic Structure Example (YAML)
Source: https://swagger.io/docs/specification/basic-structure
A fundamental OpenAPI 3.0.4 definition in YAML format, illustrating the core components of an API specification. This includes the OpenAPI version, API information, server definitions, and path definitions for endpoints.
```yaml
openapi: 3.0.4
info:
title: Sample API
description: Optional multiline or single-line description in [CommonMark](http://commonmark.org/help/) or HTML.
version: 0.1.9
servers:
- url: http://api.example.com/v1
description: Optional server description, e.g. Main (production) server
- url: http://staging-api.example.com
description: Optional server description, e.g. Internal staging server for testing
paths:
/users:
get:
summary: Returns a list of users.
description: Optional extended description in CommonMark or HTML.
responses:
"200": # status code
description: A JSON array of user names
content:
application/json:
schema:
type: array
items:
type: string
```
--------------------------------
### Generate Dynamic HTML API Documentation
Source: https://swagger.io/docs/open-source-tools/swagger-codegen/codegen-v3/about
This command generates dynamic HTML API documentation from a Swagger specification using the `-l dynamic-html` flag. After generation, the provided commands install dependencies and start a Node.js server to serve the single-page application documentation.
```bash
cd samples/dynamic-html/
npm install
node .
```
--------------------------------
### Example: Paginated Item Retrieval with Cursor (HTTP Request)
Source: https://swagger.io/docs/specification/links
This snippet demonstrates fetching the next page of items using a cursor obtained from a previous request. It includes the GET request with a 'cursor' and 'limit' parameter, facilitating sequential data retrieval.
```http
GET /items?cursor=Q1MjAwNz&limit=100
```
--------------------------------
### Start Swagger UI Development Server
Source: https://swagger.io/docs/open-source-tools/swagger-ui/development/setting-up
This command starts the local development server for Swagger UI. It provides features like hot module reloading and unminified stack traces for easier debugging. Access the UI at http://localhost:3200/.
```bash
npm run dev
```
--------------------------------
### Apply Scoped Security to Specific API Operations
Source: https://swagger.io/docs/specification/authentication
This example illustrates how to apply scoped security requirements to individual API operations rather than globally. It shows a scenario where a 'GET /users' operation requires 'read' scope, while a 'POST /users' operation requires 'write' scope, both using OAuth2 authentication.
```yaml
paths:
/users:
get:
summary: Get a list of users
security:
- OAuth2: [read]
...
post:
summary: Add a user
security:
- OAuth2: [write]
...
```
--------------------------------
### Composing Swagger UI with Swagger Editor Plugins
Source: https://swagger.io/docs/open-source-tools/swagger-editor-next
Illustrates the integration of Swagger UI with a wide array of Swagger Editor plugins. This example shows how to initialize Swagger UI and pass an array of plugins to enable various functionalities, such as different editor types, preview modes, and UI enhancements. It requires importing the 'swagger-ui' package and its CSS.
```javascript
import SwaggerUI from 'swagger-ui';
import 'swagger-ui/dist/swagger-ui.css';
import ModalsPlugin from 'swagger-editor/plugins/modals';
import DialogsPlugin from 'swagger-editor/plugins/dialogs';
import DropdownMenuPlugin from 'swagger-editor/plugins/dropdown-menu';
import DropzonePlugin from 'swagger-editor/plugins/dropzone';
import VersionsPlugin from 'swagger-editor/plugins/versions';
import EditorTextareaPlugin from 'swagger-editor/plugins/editor-textarea';
import EditorMonacoPlugin from 'swagger-editor/plugins/editor-monaco';
import EditorMonacoLanguageApiDOMPlugin from 'swagger-editor/plugins/editor-monaco-language-apidom';
import EditorContentReadOnlyPlugin from 'swagger-editor/plugins/editor-content-read-only';
import EditorContentOriginPlugin from 'swagger-editor/plugins/editor-content-origin';
import EditorContentTypePlugin from 'swagger-editor/plugins/editor-content-type';
import EditorContentPersistencePlugin from 'swagger-editor/plugins/editor-content-persistence';
import EditorContentFixturesPlugin from 'swagger-editor/plugins/editor-content-fixtures';
import EditorPreviewPlugin from 'swagger-editor/plugins/editor-preview';
import EditorPreviewSwaggerUIPlugin from 'swagger-editor/plugins/editor-preview-swagger-ui';
import EditorPreviewAsyncAPIPlugin from 'swagger-editor/plugins/editor-preview-asyncapi';
import EditorPreviewApiDesignSystemsPlugin from 'swagger-editor/plugins/editor-preview-api-design-systems';
import TopBarPlugin from 'swagger-editor/plugins/top-bar';
import SplashScreenPlugin from 'swagger-editor/plugins/splash-screen';
import LayoutPlugin from 'swagger-editor/plugins/layout';
import EditorSafeRenderPlugin from 'swagger-editor/plugins/editor-safe-render';
SwaggerUI({
url: 'https://petstore.swagger.io/v2/swagger.json',
dom_id: '#swagger-editor',
plugins: [
ModalsPlugin,
DialogsPlugin,
DropdownMenuPlugin,
DropzonePlugin,
VersionsPlugin,
EditorTextareaPlugin,
EditorMonacoPlugin,
EditorMonacoLanguageApiDOMPlugin,
EditorContentReadOnlyPlugin,
EditorContentOriginPlugin,
EditorContentTypePlugin,
EditorContentPersistencePlugin,
EditorContentFixturesPlugin,
EditorPreviewPlugin,
EditorPreviewSwaggerUIPlugin,
EditorPreviewAsyncAPIPlugin,
EditorPreviewApiDesignSystemsPlugin,
TopBarPlugin,
SplashScreenPlugin,
LayoutPlugin,
EditorSafeRenderPlugin,
],
layout: 'StandaloneLayout',
});
```
--------------------------------
### Path and Query Parameter Serialization Example (YAML)
Source: https://swagger.io/docs/specification/serialization
An OpenAPI definition in YAML format demonstrating a path parameter 'id' with 'matrix' style and 'explode: true', and a query parameter 'metadata' with default 'form' style.
```yaml
paths:
# /users;id=3;id=4?metadata=true
/users{id}:
get:
parameters:
- in: path
name: id
required: true
schema:
type: array
items:
type: integer
minItems: 1
style: matrix
explode: true
- in: query
name: metadata
schema:
type: boolean
# Using the default serialization for query parameters:
# style=form, explode=false, allowReserved=false
responses:
'200':
description: A list of users
```
--------------------------------
### Combine Path and Operation Level Parameters (YAML)
Source: https://swagger.io/docs/specification/describing-parameters
This YAML example shows how parameters defined at the path level are inherited by operations, and how additional parameters can be defined at the operation level. The `id` parameter is common to `/users/{id}`, and the `get` operation adds a `metadata` query parameter. This demonstrates a hierarchical approach to parameter definition.
```yaml
paths:
/users/{id}:
parameters:
- in: path
name: id
schema:
type: integer
required: true
description: The user ID.
get:
summary: Gets a user by ID
parameters:
- in: query
name: metadata
schema:
type: boolean
required: false
description: If true, the endpoint returns only the user metadata.
responses:
"200":
description: OK
```
--------------------------------
### Initialize Husky for Git Hooks (Optional)
Source: https://swagger.io/docs/open-source-tools/swagger-ui/development/setting-up
This command initializes Husky, a tool for managing Git hooks. This step is optional but recommended for maintaining code quality during development.
```bash
npx husky init
```
--------------------------------
### Install Swagger Codegen using Homebrew
Source: https://swagger.io/docs/open-source-tools/swagger-codegen/codegen-v3/prerequisites
Installs Swagger Codegen on macOS using the Homebrew package manager. This is a convenient method for Mac users to install the tool. Requires Homebrew to be installed.
```bash
brew install swagger-codegen
```
--------------------------------
### Clone Swagger UI Repository
Source: https://swagger.io/docs/open-source-tools/swagger-ui/development/setting-up
This command clones the Swagger UI repository from GitHub to your local machine. Ensure you have Git installed.
```bash
git clone https://github.com/swagger-api/swagger-ui.git
```
--------------------------------
### Example: Create User Operation (HTTP Request)
Source: https://swagger.io/docs/specification/links
This snippet demonstrates an HTTP POST request to create a new user. It includes the request line, host, content type, and a JSON payload with user details. The expected output is a 201 Created status with the user's ID.
```http
POST /users HTTP/1.1
Host: example.com
Content-Type: application/json
{
"name": "Alex",
"age": 27
}
```
--------------------------------
### Server URL Example
Source: https://swagger.io/docs/specification/api-host-and-base-path
Demonstrates a basic API server URL with a base path and query parameters.
```APIDOC
## GET /users
### Description
Retrieves a list of users, optionally filtered by role and status.
### Method
GET
### Endpoint
`/users`
### Query Parameters
- **role** (string) - Optional - Filters users by their role (e.g., 'admin').
- **status** (string) - Optional - Filters users by their status (e.g., 'active').
### Request Example
```
GET https://api.example.com/v1/users?role=admin&status=active
```
### Response
#### Success Response (200)
- **users** (array) - A list of user objects.
- **id** (string) - The user's unique identifier.
- **name** (string) - The user's name.
- **role** (string) - The user's role.
- **status** (string) - The user's status.
#### Response Example
```json
{
"users": [
{
"id": "user123",
"name": "John Doe",
"role": "admin",
"status": "active"
}
]
}
```
```
--------------------------------
### Example Path Parameter Definitions
Source: https://swagger.io/docs/specification/describing-parameters
Illustrates different ways to define path parameters in URLs. This includes single parameters, multiple parameters in a nested path, and parameters used for file formats. These examples show the flexibility in structuring API endpoints.
```text
GET /users/{id}
GET /cars/{carId}/drivers/{driverId}
GET /report.{format}
```