Creating a Simple API Endpoint
🧩 Creating a Simple API Endpoint
Let’s build a ProductsController
that supports basic CRUD operations.
🛒 Product Model
public class Product
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public decimal Price { get; set; }
}
🔧 ProductsController.cs
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
private static readonly List<Product> _products = new();
[HttpGet]
public ActionResult<IEnumerable<Product>> GetAll() => _products;
[HttpGet("{id}")]
public ActionResult<Product> Get(int id)
{
var product = _products.FirstOrDefault(p => p.Id == id);
return product is null ? NotFound() : Ok(product);
}
[HttpPost]
public ActionResult<Product> Create(Product product)
{
product.Id = _products.Count + 1;
_products.Add(product);
return CreatedAtAction(nameof(Get), new { id = product.Id }, product);
}
[HttpPut("{id}")]
public IActionResult Update(int id, Product updatedProduct)
{
var product = _products.FirstOrDefault(p => p.Id == id);
if (product is null) return NotFound();
product.Name = updatedProduct.Name;
product.Price = updatedProduct.Price;
return NoContent();
}
[HttpDelete("{id}")]
public IActionResult Delete(int id)
{
var product = _products.FirstOrDefault(p => p.Id == id);
if (product is null) return NotFound();
_products.Remove(product);
return NoContent();
}
}