Swagger/OpenAPI

Your API's auto-generated documentation. No more Postman collections.

The Rule: If your API has no Swagger, frontend teams will hate you. If it has good Swagger, they can build without talking to you.

1. What Problem Does Swagger Solve?

Old way: You write API. Then write Word doc: "GET /api/users returns User object". Doc gets outdated in 2 days.

Swagger way: You write API code. Swagger reads your C# and generates live docs + "Try it out" button automatically.

๐ŸŽฏ Real Zomato Scenario

Backend team ships GET /api/restaurants. Frontend team opens https://api.zomato.com/swagger. Sees all endpoints, models, can test with 1 click. Zero meetings needed.

2. Enable Swagger - Already Done in .NET 8

When you created "ASP.NET Core Web API" project with "Enable OpenAPI support" checked, you already have it.

Check Program.cs:

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer(); // Reads your controllers
builder.Services.AddSwaggerGen(); // Generates Swagger UI

var app = builder.Build();
if (app.Environment.IsDevelopment()) {
    app.UseSwagger(); // Generates /swagger/v1/swagger.json
    app.UseSwaggerUI(); // Serves /swagger UI
}
app.MapControllers();
app.Run();

Run F5 โ†’ Go to https://localhost:xxxx/swagger Youโ€™ll see all your controllers.

3. Make Swagger Useful - XML Comments + Examples

Problem: Swagger shows string name but not what "name" means.

Fix 1: XML Comments

1. Project โ†’ Properties โ†’ Build โ†’ Output โ†’ Check "Documentation file"
2. Program.cs โ†’ Add: builder.Services.AddSwaggerGen(c => { var xml = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; c.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xml)); });

Now add comments to your code:

/// 
/// Gets a restaurant by its unique ID
/// 
/// The restaurant ID. Must be > 0
/// The restaurant details
/// Restaurant found
/// Restaurant not found
[HttpGet("{id}")]
[ProducesResponseType(200)]
[ProducesResponseType(404)]
public ActionResult<Restaurant> Get(int id) {...}

Result: Swagger now shows description, params, possible responses. Frontend loves you.

Career-Killer Mistake: Shipping API with no XML docs + no [ProducesResponseType].
Swagger just shows "200 OK" with no model. Frontend team has to ping you: "What does this return?"
Fix: Add [ProducesResponseType(200, Type = typeof(Restaurant))] + XML comments. Your API is now self-documenting.

Quick Check ๐Ÿง 

Swagger done. Next: Authentication & JWT - How to add login to your API. This is where most apps become real. Continue โ†’

Comments on Swagger/OpenAPI (0)

No comments yet. Be the first to share your thoughts!