Junior — Middle
Do you follow REST principles when creating API controllers?
sobes.tech AI
Answer from AI
Yes, when creating API controllers, I try to follow REST principles to ensure convenience and predictability of interaction with the service. The main REST principles I consider:
- Use of proper HTTP methods: GET for retrieving data, POST for creating, PUT/PATCH for updating, DELETE for deleting.
- Clear URL hierarchy reflecting resource structure, for example
/api/products/123. - Statelessness, so each request contains all necessary information.
- Use of standard HTTP response codes to inform the client about the operation result.
An example of a simple REST API controller in C# using ASP.NET Core:
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
[HttpGet("{id}")]
public IActionResult GetProduct(int id)
{
var product = _repository.GetProductById(id);
if (product == null) return NotFound();
return Ok(product);
}
[HttpPost]
public IActionResult CreateProduct(Product product)
{
_repository.AddProduct(product);
return CreatedAtAction(nameof(GetProduct), new { id = product.Id }, product);
}
// Other methods PUT, DELETE, etc.
}
This approach simplifies support and scaling of the API.