OpenAPI, Scalar and API versioning
OpenAPI is a machine-readable contract of your API generated from the code; Scalar turns it into interactive docs; API versioning lets you ship breaking changes as v2 while v1 clients keep working. This video also covers JSON Patch for partial updates.
49.1 Why is it used?
- Frontend and mobile teams need to know which endpoints exist and what each request sends and returns.
- Docs in a Word file or chat go stale the moment the code changes, and clients break in production.
- A contract generated from code is always current and can drive docs UIs and client code generators.
- Versioning protects old clients when the response shape changes.
49.2 The bug: an API, but no docs
var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllers();builder.Services.AddSingleton<ProductStore>(); var app = builder.Build(); app.MapControllers();app.Run();$ curl -i localhost:5049/api/productsHTTP/1.1 200 OKContent-Type: application/json; charset=utf-8[{"id":1,"name":"Mixer Grinder","price":2499,"stock":12}, {"id":2,"name":"Steel Bottle","price":399,"stock":40}] $ curl -i localhost:5049/openapi/v1.jsonHTTP/1.1 404 Not FoundContent-Length: 0- The API works, but /openapi/v1.json gives 404: there is no machine-readable description.
- Step 1
1.Docs written by hand in Word or chat
- Step 2
2.Code changes
- Step 3
3.Doc is now outdated
- Step 4
4.Client sends a wrong field -> bug in production
Needed: a contract generated from code = OpenAPI
49.3 Fix: AddOpenApi + MapOpenApi
var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllers();builder.Services.AddSingleton<ProductStore>();builder.Services.AddOpenApi(); var app = builder.Build(); if (app.Environment.IsDevelopment()){ app.MapOpenApi();} app.MapControllers();app.Run();$ curl localhost:5049/openapi/v1.json{ "openapi": "3.1.1", "info": { "title": "Shop | v1", "version": "1.0.0" }, "servers": [ { "url": "http://localhost:5049/" } ], "paths": { "/api/products": { "get": ... }, "/api/products/{id}": { "get": ..., "patch": ... } }, "components": { "schemas": { "ProductDto": ..., "ProblemDetails": ... } }}- AddOpenApi is already in the .NET 10 webapi template.
- MapOpenApi serves the document at /openapi/v1.json; it sits inside IsDevelopment so it is not public in production.
- The output is OpenAPI 3.1 JSON with the title, all paths and schemas like ProductDto and ProblemDetails.
49.4 Metadata: summary + responses
[HttpGet("{id:int}")][EndpointSummary("Get one product by id")][ProducesResponseType<ProductDto>(200)][ProducesResponseType(404)]public ActionResult<ProductDto> GetById(int id){ var product = store.Find(id); if (product is null) return NotFound(); return product.ToDto();}$ curl localhost:5049/openapi/v1.json"/api/products/{id}": { "get": { "summary": "Get one product by id", "parameters": [ { "name": "id", "in": "path" } ], "responses": { "200": { "description": "OK", ... ProductDto }, "404": { "description": "Not Found", ... ProblemDetails } }- [EndpointSummary] adds a short description next to the endpoint in the docs.
- [ProducesResponseType<ProductDto>(200)] and [ProducesResponseType(404)] list every possible response, so clients know in advance what a missing product returns.
49.5 Scalar: interactive API docs
// dotnet add package Scalar.AspNetCoreusing Scalar.AspNetCore; // services: same as before var app = builder.Build(); if (app.Environment.IsDevelopment()){ app.MapOpenApi(); app.MapScalarApiReference();} app.MapControllers();app.Run();# Shop | v1 (browser: /scalar)OpenAPI 3.1.1 · Version 1.0.0Server: http://localhost:5049/ProductsGET /api/productsGET /api/products/{id} · Get one product by idPATCH /api/products/{id}Models: JsonPatchDocument, ProblemDetails, ProductDto # Test RequestGET /api/products/{id}Path parameter: id = 1[button] Send200 OK{ "id": 1, "name": "Mixer Grinder", "price": 2499, "stock": 12 }- JSON is for machines; Scalar serves a readable page at /scalar from the same OpenAPI JSON.
- Every endpoint shows parameters and schemas; Test Request sends a real call and shows the response on the same page.
- Step 1
1.Controllers: routes, types, attributes
- Step 2
2.ApiExplorer collects the metadata
- Step 3
3.MapOpenApi builds openapi/v1.json
- Step 4
4.Scalar and client generators read the same document
Single source of truth: your code
49.6 JSON Patch: change only the price
[HttpPatch("{id:int}")]public ActionResult<ProductDto> Patch(int id, JsonPatchDocument<ProductPatch> patch){ var product = store.Find(id); if (product is null) return NotFound(); var changes = product.ToPatch(); patch.ApplyTo(changes, e => ModelState .AddModelError("patch", e.ErrorMessage)); if (!ModelState.IsValid) return ValidationProblem(ModelState); product.Apply(changes); return product.ToDto();}$ curl -i -X PATCH localhost:5049/api/products/1 \ -H "Content-Type: application/json-patch+json" \ -d '[{"op":"replace","path":"/price","value":2299}]'HTTP/1.1 200 OK{"id":1,"name":"Mixer Grinder","price":2299,"stock":12} $ curl -i -X PATCH localhost:5049/api/products/1 \ -H "Content-Type: application/json-patch+json" \ -d '[{"op":"replace","path":"/id","value":7}]'HTTP/1.1 400 Bad RequestContent-Type: application/problem+json; charset=utf-8{ "title": "One or more validation errors occurred.", "status": 400, "errors": { "patch": [ "The target location specified by path segment 'id' was not found." ] } }- To change only the price you should not send the whole product with PUT; the client sends operations like replace /price.
- .NET 10 has a new System.Text.Json based JsonPatch package; Content-Type is application/json-patch+json.
- Copy the product into ProductPatch, which has only the allowed fields, so the id cannot be changed.
- ApplyTo reports errors into ModelState, which becomes a 400 ValidationProblem.
49.7 API versioning with Asp.Versioning
builder.Services.AddApiVersioning(o =>{ o.DefaultApiVersion = new ApiVersion(1); o.ReportApiVersions = true;}).AddMvc().AddApiExplorer(o =>{ o.GroupNameFormat = "'v'V"; o.SubstituteApiVersionInUrl = true;}); builder.Services.AddOpenApi("v1");builder.Services.AddOpenApi("v2");$ curl -s localhost:5049/openapi/v1.json | grep '"/api' "/api/v1/products": { "/api/v1/products/{id}": {$ curl -s localhost:5049/openapi/v2.json | grep '"/api' "/api/v2/products/{id}": {- Package: Asp.Versioning.Mvc.ApiExplorer. DefaultApiVersion = 1.
- ReportApiVersions = true lists supported versions in the api-supported-versions response header.
- AddMvc turns versioning on for controllers; AddApiExplorer creates a group per version, so AddOpenApi("v1") and AddOpenApi("v2") make separate documents.
- SubstituteApiVersionInUrl puts the real version into the paths (/api/v1/products).
49.8 V2 controller: a new response shape
[ApiController][ApiVersion(2)][Route("api/v{version:apiVersion}/products")]public class ProductsController( ProductStore store) : ControllerBase{ [HttpGet("{id:int}")] public ActionResult<ProductV2Dto> Get(int id) { var p = store.Find(id); if (p is null) return NotFound(); return new ProductV2Dto(p.Id, p.Name, new Money(p.Price, "INR"), p.Stock); }}namespace Shop.V1; [ApiController][ApiVersion(1)][Route("api/v{version:apiVersion}/products")]public class ProductsController( ProductStore store) : ControllerBase{ // GetAll, GetById, Patch}$ curl -i localhost:5049/api/v1/products/1HTTP/1.1 200 OKapi-supported-versions: 1.0, 2.0{"id":1,"name":"Mixer Grinder","price":2499,"stock":12} $ curl -i localhost:5049/api/v2/products/1HTTP/1.1 200 OKapi-supported-versions: 1.0, 2.0{"id":1,"name":"Mixer Grinder", "price":{"amount":2499,"currency":"INR"},"stock":12}- In v2 the price becomes a Money object (amount + currency): a breaking change, so it gets a new version.
- V2 controller: [ApiVersion(2)] and the {version:apiVersion} route placeholder; V1 just gets [ApiVersion(1)] and the same route.
- v1 still returns the flat price; both responses carry api-supported-versions: 1.0, 2.0.
- Step 1
1.GET /api/v2/products/1
- Step 2
2.Route {version:apiVersion} reads 2
- Step 3
3.Controller with [ApiVersion(2)] is selected
- Step 4
4.Returns ProductV2Dto with Money price
- Step 5
5.Header api-supported-versions: 1.0, 2.0
v1 clients keep calling /api/v1 unchanged
49.9 Checkpoint: what if v3 is requested?
$ curl -i localhost:5049/api/v3/products/1HTTP/1.1 404 Not FoundContent-Length: 0$ curl -i localhost:5049/api/products/1HTTP/1.1 404 Not FoundContent-Length: 0- Both give 404: the route requires a version segment and no controller declares v3.
- Give clients enough time before removing a version.
49.10 Comparison: PUT vs PATCH, and versioning styles
| Option | What it means | Note |
|---|---|---|
| PUT | Send the whole resource | Simple; overwrites every field |
| PATCH (JSON Patch) | Send a list of operations | Only the changed fields; use a patch class |
| URL segment /api/v1/... | Version in the path | Used here; visible and cache friendly |
| Query string / header | ?api-version=2 or a header | Also supported by Asp.Versioning |
49.11 Common mistakes
- Declaring only some response types: once any ProducesResponseType is added, ApiExplorer no longer adds the automatic 200, so write 200 explicitly.
- Myth: .NET 10 has no Swagger, so no docs. Swagger is the old name of the OpenAPI spec; Swashbuckle (AddSwaggerGen, UseSwaggerUI) is a third-party package in older projects. Since .NET 9 the template uses built-in OpenAPI and you pick the UI, e.g. Scalar.
- Exposing OpenAPI/Scalar publicly in production without protection.
- Applying JSON Patch directly to the entity (the client could change the id).
// Wrong: only 404 declared -> 200 missing from the docs[HttpGet("{id:int}")][ProducesResponseType(404)]public ActionResult<ProductDto> GetById(int id) // Right: every response explicit[HttpGet("{id:int}")][ProducesResponseType<ProductDto>(200)][ProducesResponseType(404)]public ActionResult<ProductDto> GetById(int id)49.12 Rules for OpenAPI and versioning
- Generate docs from code: AddOpenApi + MapOpenApi.
- Summary + all response types on every action.
- Map OpenAPI and Scalar only in Development, or protect them.
- JSON Patch: separate patch class, errors -> 400.
- Breaking change = new version; keep v1 running until clients move.
49.13 Interview tips
- I generate the OpenAPI document with built-in AddOpenApi/MapOpenApi and keep it accurate with EndpointSummary and ProducesResponseType.
- For readable docs I use Scalar, enabled only in Development.
- For breaking changes I use URL segment versioning with Asp.Versioning, one OpenAPI document per version, so v1 clients never break.
- Swagger is the old name for OpenAPI; Swashbuckle is optional, not built in.