A web API action method handles an HTTP request and produces a response for a client. Actions belong to controllers, which typically group related operations around a resource. Unlike an MVC action that renders a Razor view, a web API action generally returns data or an HTTP result. section 19.2 section 20.1 section 19.5.1
Routing selects an action for the incoming request. Model binding supplies its parameters from request data, and validation records errors in ModelState. The action can then call application services rather than embedding business logic in the controller. section 20.2 section 19.3
Return a list of fruit
A FruitController derived from ControllerBase can define an action with `[HttpGet("fruit")]` and `public IEnumerable<string> Index()`. Returning a list containing Pear, Lemon, and Peach from the method makes a GET request to `/fruit` return the list serialized as JSON. section 20.1
Listing 20.2 A simple web API controller
[ApiController] #1
public class FruitController : ControllerBase #2
{
List<string> _fruit = new List<string> #3
{ #3
"Pear", #3
"Lemon", #3
"Peach" #3
}; #3
[HttpGet("fruit")] #4
public IEnumerable<string> Index() #5
{ #6
return _fruit; #6
} #6
}
See the complete controller, including the route attribute and action return type. section 20.1
Use attribute routing to associate actions with route templates. An action can have multiple templates; controller-level and action-level attributes can also combine into a final template. By default, controller and action names do not determine the URL. Attributes such as `[HttpGet]` and `[HttpPost]` distinguish actions by HTTP verb. section 20.3 section 20.7
Return data or an error
An action declared as `ActionResult<string>` can return a fruit for a valid index or `NotFound()` when the index is out of range. The data result produces a 200 response; with `[ApiController]`, the error response uses the ProblemDetails format. section 20.1
The `[ApiController]` attribute adds conventions that reduce repeated code, including automatic 400 responses for invalid requests and ProblemDetails for status-code errors. API models hold the data serialized for clients; they differ from view models used to render HTML. section 20.7
For a controller-only API, register controller services with `AddControllers()` and map actions as endpoints with `MapControllers()`. This setup omits the services used to render Razor views. section 20.1


