Understanding RESTful APIs

What is a RESTful API?

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.

  • Stateless: Each request from a client to a server must contain all the information needed to process it.
  • Resource-Based: APIs expose resources (e.g., users, products) via endpoints.
  • Standard Methods: HTTP methods like GET, POST, PUT, and DELETE are used to perform CRUD operations on resources.

Key Features of RESTful APIs

RESTful APIs follow specific principles that make them easy to use and integrate:

  • Uniform Interface: Consistent endpoints and responses.
  • Client-Server Architecture: The client (frontend) and server (backend) are separated.
  • Stateless Communication: No session state is stored on the server.
  • Cacheable: Responses can be cached to improve performance.

Basic Example of a RESTful API

Here’s a step-by-step guide to creating a simple RESTful API using ASP.NET Core:

1. Define the Model


// 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.

2. Create the Controller


// 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.

3. Test the API


// 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.