Introduction to Web APIs
- An API (Application Programming Interface) allows different applications to communicate in a formalized way.
- Web APIs, or web services, expose data over the internet, typically for consumption by other applications (e.g., mobile apps).
- Instead of returning HTML for a browser, web APIs usually return data in a machine-readable format like JSON (JavaScript Object Notation).
Creating a Simple API Endpoint
API endpoints are configured in the startup.cs file within the Configure method's app.UseEndpoints() block. You can create a simple, low-level GET endpoint using the endpoints.MapGet() method.
Note
This manual approach is useful for understanding the fundamentals. More advanced and maintainable methods, like using API Controllers, are often preferred for real-world applications.
Endpoint Implementation Example
The following demonstrates creating an endpoint at the /products URL that returns a list of products as JSON.
Route Definition: Define the path and the logic to execute.
endpoints.MapGet("/products", context => { ... });Service Retrieval: Inside the lambda, manually access registered services from the application's service container.
var productService = app.ApplicationServices.GetRequiredService<JsonFileProductService>();var products = productService.GetProducts();JSON Serialization: Convert the C# object collection into a JSON string.
var json = JsonSerializer.Serialize<IEnumerable<Product>>(products);Response: Write the JSON string back to the client as an asynchronous operation.
return context.Response.WriteAsync(json);
Important using Statements
Visual Studio's "light bulb" helper is useful for adding required using statements for new types and methods you introduce.
System.Text.Json: Required forJsonSerializer.Microsoft.AspNetCore.Http: Required forcontext.Response.WriteAsync.YourApp.Models: Required to reference yourProductclass.
Testing Your API
- After running your application, you can test the endpoint by navigating to its URL (e.g.,
https://localhost:5001/products). - The browser will display the raw JSON string.
Tip
Browser extensions like JSONView can automatically format raw JSON, making it much more readable for humans during development and testing.
