Junior — Middle
Can you explain the principles and features of RESTful API?
sobes.tech AI
Answer from AI
RESTful API is an architectural style for creating web services based on REST (Representational State Transfer) principles. Key principles and features:
- Resource-oriented: all objects (resources) have unique URIs.
- Use of standard HTTP methods:
- GET — retrieve a resource
- POST — create a resource
- PUT — update a resource
- DELETE — delete a resource
- HTTP status codes: to inform the client about the request result (e.g., 200 OK, 404 Not Found).
- Stateless: the server does not store client state between requests.
- Use of data formats: most commonly JSON or XML for data transfer.
Example of a simple 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.GetById(id);
if (product == null) return NotFound();
return Ok(product);
}
[HttpPost]
public IActionResult CreateProduct(Product product)
{
_repository.Add(product);
return CreatedAtAction(nameof(GetProduct), new { id = product.Id }, product);
}
}