Junior — Middle
Explain what is meant by RESTful API and how it works.
sobes.tech AI
Answer from AI
RESTful API is an architectural style for creating web services that uses the HTTP protocol and REST principles (Representational State Transfer). The main idea is to provide resources (data) through unique URLs, using standard HTTP methods: GET (retrieve data), POST (create), PUT/PATCH (update), DELETE (delete).
RESTful API works as follows: the client sends an HTTP request to the server specifying the resource and method, the server processes the request and returns a response with data in JSON, XML, or other formats. This approach simplifies interaction between client and server, making the API easy to understand and scalable.
An example of a simple RESTful API in C# using ASP.NET Core:
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
[HttpGet]
public IEnumerable<Product> GetAll() => productService.GetAll();
[HttpGet("{id}")]
public ActionResult<Product> GetById(int id)
{
var product = productService.GetById(id);
if (product == null) return NotFound();
return product;
}
[HttpPost]
public IActionResult Create(Product product)
{
productService.Add(product);
return CreatedAtAction(nameof(GetById), new { id = product.Id }, product);
}
}