Sobes.tech
Junior — Middle

What does it mean that a controller implements REST principles and how to define a RESTful controller in a project?

sobes.tech AI

Answer from AI

A controller implementing REST principles adheres to the REST (Representational State Transfer) architectural style, which involves:

  • Using HTTP methods (GET, POST, PUT, DELETE, etc.) for resource operations.
  • Identifying resources via URIs.
  • Being stateless between requests.
  • Using standard HTTP response codes.
  • Transmitting data in JSON, XML, or other formats.

In C#, a RESTful controller is typically defined using the [ApiController] attribute and routing with [Route]. Controller methods correspond to HTTP methods via [HttpGet], [HttpPost], etc.

Example of a RESTful controller in ASP.NET Core:

[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
    [HttpGet]
    public IActionResult GetAll() { /* return list of products */ }

    [HttpGet("{id}")]
    public IActionResult GetById(int id) { /* return product by id */ }

    [HttpPost]
    public IActionResult Create(Product product) { /* create product */ }

    [HttpPut("{id}")]
    public IActionResult Update(int id, Product product) { /* update product */ }

    [HttpDelete("{id}")]
    public IActionResult Delete(int id) { /* delete product */ }
}

Such a controller conforms to REST as it operates on resources via HTTP methods and URIs, does not store state between requests, and returns standard responses.