A RESTful API (Representational State Transfer) is an architectural style for building web services that interact over HTTP. RESTful APIs allow different systems to communicate and exchange data using a standardized approach.
GET
, POST
,
PUT
, and DELETE
are used to perform CRUD operations on resources.
RESTful APIs follow specific principles that make them easy to use and integrate:
Here’s a step-by-step guide to creating a simple RESTful API using ASP.NET Core:
// Models/Product.cs
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
This is the Product
model, representing the data structure for our resource.
// Controllers/ProductController.cs
[ApiController]
[Route("api/[controller]")]
public class ProductController : ControllerBase
{
private static List<Product> products = new List<Product>
{
new Product { Id = 1, Name = "Laptop", Price = 1200 },
new Product { Id = 2, Name = "Mouse", Price = 25 }
};
// GET: api/product
[HttpGet]
public ActionResult<IEnumerable<Product>> GetProducts()
{
return Ok(products);
}
// GET: api/product/1
[HttpGet("{id}")]
public ActionResult<Product> GetProduct(int id)
{
var product = products.FirstOrDefault(p => p.Id == id);
if (product == null) return NotFound();
return Ok(product);
}
// POST: api/product
[HttpPost]
public ActionResult CreateProduct(Product product)
{
products.Add(product);
return CreatedAtAction(nameof(GetProduct), new { id = product.Id }, product);
}
// PUT: api/product/1
[HttpPut("{id}")]
public ActionResult UpdateProduct(int id, Product updatedProduct)
{
var product = products.FirstOrDefault(p => p.Id == id);
if (product == null) return NotFound();
product.Name = updatedProduct.Name;
product.Price = updatedProduct.Price;
return NoContent();
}
// DELETE: api/product/1
[HttpDelete("{id}")]
public ActionResult DeleteProduct(int id)
{
var product = products.FirstOrDefault(p => p.Id == id);
if (product == null) return NotFound();
products.Remove(product);
return NoContent();
}
}
This controller provides endpoints for all CRUD operations on the Product
resource.
// Example HTTP Requests:
// GET all products: GET http://localhost:5000/api/product
// GET a single product: GET http://localhost:5000/api/product/1
// Add a new product: POST http://localhost:5000/api/product
// Update a product: PUT http://localhost:5000/api/product/1
// Delete a product: DELETE http://localhost:5000/api/product/1
Use tools like Postman or cURL to test these endpoints.