# Versioning, Evolution and Breaking Changes — OpenAPI / Swagger

Source: https://www.skillbyai.com/en/openapi/d-versioning

> Evolve APIs safely and detect breaking changes in OpenAPI documents.

## Change without breaking clients

APIs change; the goal is to change them without breaking existing clients. **Backward-compatible** changes include adding new endpoints, adding **optional** request fields or parameters, and adding response fields (provided clients ignore unknown fields). **Breaking** changes include removing or renaming endpoints, fields or parameters, making an optional input **required**, changing types or formats, narrowing enums in requests, adding enum values that strict clients cannot handle, changing status codes, and changing authentication requirements. Strategies: keep changes additive; mark old elements **`deprecated: true`** with a description of the replacement and a sunset date (the `Sunset` and `Deprecation` HTTP headers can signal this at run time); introduce a **new major version** (`/v2` path, header or media type) only for unavoidable breaks; and run old and new versions side by side during migration. Automate detection: tools such as **oasdiff** and other OpenAPI diff tools compare the previous and new documents in CI and fail the build on breaking changes. Use semantic versioning in `info.version` to communicate impact.

## Detecting breaking changes in CI

Compare the main branch's document with the pull request's version.

```bash
# fetch the published contract from main and compare it with the PR version
git show origin/main:api/openapi.yaml > /tmp/openapi-main.yaml

oasdiff breaking /tmp/openapi-main.yaml api/openapi.yaml --fail-on ERR
# examples of what it flags:
#   removed path GET /orders/{orderId}/invoice
#   request property 'couponCode' became required
#   response property 'total' type changed from string to number

# additive changes (new optional field, new endpoint) pass
oasdiff changelog /tmp/openapi-main.yaml api/openapi.yaml
```

## Adding rooms versus moving walls

Adding a new room to a building disturbs nobody. Moving a load-bearing wall or a staircase that people already use needs warning, a temporary route and a deadline. API changes work the same way.

**Quiz:** Which change to a public API is usually breaking?

- [ ] Adding a new optional query parameter
- [ ] Adding a new endpoint
- [ ] Adding a new field to a response
- [x] Making a previously optional request field required

*Answer:* Making a previously optional request field required. Existing clients that do not send the field would suddenly be rejected.
