Web API Concepts
This section delves into the core concepts of building Web APIs with .NET. Web APIs are fundamental for creating modern, scalable, and interoperable applications that can communicate over the web.
What is a Web API?
A Web API (Application Programming Interface) is a set of definitions, protocols, and tools for building software. In the context of the web, it's an interface that allows different applications or services to communicate with each other, typically using HTTP. .NET provides robust frameworks for creating and consuming Web APIs.
Key .NET Web API Technologies
- ASP.NET Core Web API: The modern, cross-platform, high-performance framework for building Web APIs. It's the recommended choice for new development.
- ASP.NET Web API (Legacy): An older framework, part of the ASP.NET ecosystem, primarily for .NET Framework. While still functional, ASP.NET Core offers significant advantages.
Core Concepts
1. HTTP Verbs (Methods)
Web APIs leverage standard HTTP methods to perform actions on resources:
- GET: Retrieves data.
- POST: Creates new data.
- PUT: Updates existing data (replaces the entire resource).
- PATCH: Updates existing data (applies partial modifications).
- DELETE: Removes data.
2. Resources and URIs
In a Web API, data is represented as resources. Each resource has a unique Uniform Resource Identifier (URI). For example:
/api/products
: Represents a collection of products./api/products/123
: Represents a specific product with ID 123.
3. Request and Response
Clients send HTTP requests to the API, and the API sends back HTTP responses.
- Request: Includes method, URI, headers, and potentially a body.
- Response: Includes status code, headers, and a body (often JSON or XML).
4. Data Formats
APIs commonly exchange data in formats like JSON (JavaScript Object Notation) and XML (Extensible Markup Language). ASP.NET Core Web API has built-in support for JSON serialization using System.Text.Json
or Newtonsoft.Json.
5. Status Codes
HTTP status codes indicate the outcome of a request:
- 2xx (Success): e.g.,
200 OK
,201 Created
- 3xx (Redirection): e.g.,
301 Moved Permanently
- 4xx (Client Error): e.g.,
400 Bad Request
,404 Not Found
,401 Unauthorized
- 5xx (Server Error): e.g.,
500 Internal Server Error
6. Controllers and Actions
In ASP.NET Core Web API, controllers are classes that handle incoming requests. Actions (methods within controllers) map to specific HTTP verbs and URIs.
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
// GET api/products
[HttpGet]
public IActionResult Get()
{
// Return a list of products
return Ok(new[] { "Product A", "Product B" });
}
// GET api/products/5
[HttpGet("{id}")]
public IActionResult Get(int id)
{
if (id <= 0)
{
return BadRequest("Product ID must be positive.");
}
// Find and return a specific product
return Ok($"Product {id}");
}
// POST api/products
[HttpPost]
public IActionResult Post([FromBody] string newProduct)
{
// Add the new product to storage
return CreatedAtAction(nameof(Get), new { id = 100 }, newProduct);
}
}
7. Routing
Routing maps incoming URIs to specific controller actions. Attribute routing (using attributes like [HttpGet]
, [Route]
) is the primary method in ASP.NET Core.
8. Model Binding and Validation
Model binding automatically maps incoming request data (from the URI, query string, or request body) to parameters in your controller actions. Validation ensures that the incoming data meets certain criteria.
9. Dependency Injection
.NET's built-in dependency injection container is widely used in Web APIs to manage service lifetimes and promote loose coupling.