Building and Managing RESTful APIs in ASP.NET Core
In this blog, we’ll explore how to create and manage a RESTful API using ASP.NET Core. Specifically, we'll demonstrate how to build a simple API that performs CRUD (Create, Read, Update, Delete) operations on a database entity, which can be consumed by web applications, mobile apps, or other services.
RESTful APIs are at the heart of modern web development. They allow seamless communication between client and server, making it easier to share data across platforms. While APIs can be designed using many technologies, ASP.NET Core provides a robust, high-performance framework with built-in features for security, routing, and model validation.
By the end of this blog, you’ll have a clear understanding of how to build an API from scratch in .NET, and how it can be extended to power real-world applications.
Required Components for API Creation
To build a RESTful API in ASP.NET Core, you’ll primarily work with the following:
- Models
- Define the structure of the data you want to manage (e.g., Products, Customers, Orders).
- DbContext
- A class provided by Entity Framework Core to interact with the database.
- Controllers
- Contain endpoints that handle HTTP requests such as
GET,POST,PUT, andDELETE.
- Contain endpoints that handle HTTP requests such as
Steps to Create an API in ASP.NET Core
1. Define the Model
Here’s an example of a simple Product model:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public int Stock { get; set; }
}
2. Configure the DbContext
Use Entity Framework Core to manage data storage and retrieval.
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) {}
public DbSet<Product> Products { get; set; }
}
3. Create the Controller
Add a controller to handle API endpoints.
[Route("api/[controller]")]
[ApiController]
public class ProductsController : ControllerBase
{
private readonly AppDbContext _context;
public ProductsController(AppDbContext context)
{
_context = context;
}
// GET: api/products
[HttpGet]
public async Task<ActionResult<IEnumerable<Product>>> GetProducts()
{
return await _context.Products.ToListAsync();
}
// GET: api/products/5
[HttpGet("{id}")]
public async Task<ActionResult<Product>> GetProduct(int id)
{
var product = await _context.Products.FindAsync(id);
if (product == null) return NotFound();
return product;
}
// POST: api/products
[HttpPost]
public async Task<ActionResult<Product>> CreateProduct(Product product)
{
_context.Products.Add(product);
await _context.SaveChangesAsync();
return CreatedAtAction(nameof(GetProduct), new { id = product.Id }, product);
}
// PUT: api/products/5
[HttpPut("{id}")]
public async Task<IActionResult> UpdateProduct(int id, Product product)
{
if (id != product.Id) return BadRequest();
_context.Entry(product).State = EntityState.Modified;
await _context.SaveChangesAsync();
return NoContent();
}
// DELETE: api/products/5
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteProduct(int id)
{
var product = await _context.Products.FindAsync(id);
if (product == null) return NotFound();
_context.Products.Remove(product);
await _context.SaveChangesAsync();
return NoContent();
}
}
Updating an API Endpoint
Once your API is live, you may need to extend it—for example, adding a filter to return only products below a certain stock level.
// GET: api/products/lowstock
[HttpGet("lowstock")]
public async Task<ActionResult<IEnumerable<Product>>> GetLowStockProducts()
{
return await _context.Products
.Where(p => p.Stock < 10)
.ToListAsync();
}
This update allows clients to request only those products that require restocking, making the API more useful for inventory management.
Final Output
After setting up your API, you can test it using tools like Postman or Swagger UI (which comes built-in with .NET 6+ templates). You’ll see endpoints such as:
GET /api/products– Retrieve all productsPOST /api/products– Add a new productPUT /api/products/{id}– Update an existing productDELETE /api/products/{id}– Remove a productGET /api/products/lowstock– Get low stock products
Conclusion
By following these steps, you can quickly build and manage a RESTful API in ASP.NET Core. This provides a solid foundation for integrating web applications, mobile apps, or third-party services with your backend. Leveraging .NET for API development ensures scalability, performance, and security—making it a great choice for modern web development projects.
Comments
Post a Comment