Versioning APIs is an essential practice for maintaining the integrity of your services while accommodating changes and enhancements. Swagger, now known as OpenAPI Specification, provides a powerful framework for defining APIs, including their versions. This ensures that clients can seamlessly transition between different versions of an API without disruption. Below, you will find three diverse examples illustrating how to implement versioning in APIs using Swagger.
In this example, we’ll demonstrate how to implement versioning directly in the URL of your API endpoints. This is a common approach and allows clients to specify which version of the API they want to consume.
openapi: 3.0.0
info:
title: Sample API
description: A simple API to demonstrate versioning
version: 1.0.0
paths:
/v1/users:
get:
summary: Retrieve user list
responses:
'200':
description: A list of users
/v2/users:
get:
summary: Retrieve user list with enhanced data
responses:
'200':
description: A list of users with additional fields
In scenarios where changing the URL structure is not ideal, header versioning can be employed. This method allows clients to specify the API version in the request headers.
openapi: 3.0.0
info:
title: Sample API
description: A simple API to demonstrate header versioning
version: 1.0.0
paths:
/users:
get:
summary: Retrieve user list
parameters:
- in: header
name: Accept-Version
required: true
schema:
type: string
description: Specify the API version
responses:
'200':
description: A list of users
content:
application/json:
schema:
type: array
items:
type: object
properties:
id:
type: integer
name:
type: string
Accept-Version
header in their requests.Another effective method of versioning APIs is using query parameters. This is particularly useful for APIs that require backward compatibility while introducing new features.
openapi: 3.0.0
info:
title: Sample API
description: A simple API to demonstrate query parameter versioning
version: 1.0.0
paths:
/users:
get:
summary: Retrieve user list
parameters:
- in: query
name: version
required: true
schema:
type: string
enum: [1.0, 2.0]
description: Specify the API version
responses:
'200':
description: A list of users based on the requested version
By implementing these examples of versioning APIs with Swagger, developers can maintain backward compatibility while evolving their API offerings.