Install-Package Swashbuckle.AspNetCore -Version 6.6.2
Program.cs
builder.Services.AddControllers(); builder.Services.AddEndpointsApiExplorer(); // add this builder.Services.AddSwaggerGen(); // add this // ... if (app.Environment.IsDevelopment()) { app.UseSwagger(); // add this app.UseSwaggerUI(); // add this app.MapOpenApi(); }
http://localhost:<port>/swagger
WeatherForecastController.cs
var builder = WebApplication.CreateBuilder(args);
The controllers and some other components (like Swagger) are added to the application as services
// Add services to the container. builder.Services.AddControllers(); builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen();
As the comment above suggests, more services can be added as needed
if (app.Environment.IsDevelopment()){ app.UseSwagger(); app.UseSwaggerUI(); app.MapOpenApi(); } app.UseAuthorization(); app.MapControllers(); app.Run();
GET
http://someserver.com/api/products
GetProducts()
http://someserver.com/api/products/3
GetProduct(int id)
POST
PostProduct()
[ApiController] // Attribute routing requirement, // automatic HTTP 400 response, and more [Route("[controller]")] // HTTP GET requests are routed to this method public class WeatherForecastController : ControllerBase { //... } // ... [HttpGet] // URIs with "/weatherforecast" are routed to this class public IEnumerable<WeatherForecast> Get() { //... }
[Route("api")]
[HttpGet]
GET <localhost>/api
[HttpGet("products")]
GET <localhost>/api/products
[HttpGet("products/{id}")]
GET <localhost>/api/products/12
[HttpPost("products")]
POST <localhost>/api/products
http://localhost:<port>/api/weatherforecast
http://localhost:<port>/weatherforecast
You can see the route change in the Swagger UI GET method.
[Route("api")] // class declaration // ... [HttpGet("list/{someText}")] public string[] GetArrayOfStrings(string someText) { return Enumerable.Range(1, 5).Select(index => new string(someText)) .ToArray(); }
[Route("api")] // class declaration // ... [HttpGet("list/{someText?}")] public string[] GetArrayOfStrings(string someText = "default") { return Enumerable.Range(1, 5).Select(index => new string(someText)) .ToArray(); }
:
404
[HttpGet("products/{id:int}")] // Required type: int [HttpGet("list/{value:length(3,40)}")] // Required length: 3-40
IEnumerable
WeatherForecast
List
string
http://localhost:<port>/api/numberlist/k
k
1
http://localhost:<port>/api/numberlist/5
[1,2,3,4,5]
PUT
DELETE
Run the Weather API program, and test both methods with Postman.
APIs are interfaces that applicaitons use to communicate with each other Xamarin for mobile Use of NuGet packages add modularity and decrease the minimum memory footprint of your projects