Introduction
In a REST API, the URL is only one part of the contract. The HTTP method and the returned status code are equally important. A client uses GET /api/products/5 to express that it wants to read a resource, while DELETE /api/products/5 expresses that it wants to remove one.
In this lesson, we will distinguish GET, POST, PUT, PATCH, and DELETE. We will then implement listing, detail retrieval, creation, full update, and deletion for a Product resource using ASP.NET Core Web API and Entity Framework Core. The implementation will deliberately produce 200 OK, 201 Created, 204 No Content, 400 Bad Request, and 404 Not Found at the appropriate times.
1. Responsibilities of HTTP methods
| Method | Purpose | Typical use | Common responses |
|---|---|---|---|
| GET | Read a resource | Retrieve a product collection or a specific product | 200, 404 |
| POST | Create a new resource | Add a product | 201, 400 |
| PUT | Replace or fully update a resource | Send all mutable product fields | 204, 400, 404 |
| PATCH | Partially update a resource | Change only the price or stock quantity | 200, 204, 400, 404 |
| DELETE | Delete a resource | Remove a product | 204, 404 |
GET is safe and idempotent in normal usage because it does not change server state. PUT and DELETE should be designed to be idempotent as well. Repeating the same delete request should not produce an additional deletion effect. POST is generally not idempotent; submitting the same request twice can create two resources.
PUT versus PATCH
PUT is used to replace a resource representation. The client is therefore expected to send all relevant mutable fields. PATCH carries a partial modification. If only the price changes, a PATCH request may contain only a price property.
PATCH can be implemented with JSON Patch or JSON Merge Patch. To keep this lesson focused on a complete and understandable CRUD flow, the controller implements updating with PUT. We will still identify where PATCH belongs and why it should not be treated as an informal version of PUT.
2. Choosing status codes
Status codes allow clients to interpret results predictably. Use 200 OK when a read succeeds and the response includes a representation. Use 201 Created when a new resource is created. A well-designed 201 response also includes a Location header pointing to the new resource.
Use 204 No Content when the operation succeeds but a response body is unnecessary. This is common for PUT and DELETE operations. Return 400 Bad Request when the client sends invalid input or violates a request rule. Return 404 Not Found when the requested resource does not exist.
- 200: The read succeeded and a response body is available.
- 201: A new resource was created.
- 204: The operation succeeded without a response body.
- 400: The request is invalid.
- 404: The requested resource could not be found.
Returning 200 for every successful operation is not a good API contract. Although POST can technically return 200, 201 communicates creation more accurately. Likewise, DELETE does not need to return the deleted object when the client only needs confirmation, so 204 is usually clearer.
3. The Product entity and DbContext
First, create the entity that represents a database row. This example includes basic rules: the name is required, the name and description have maximum lengths, and price and stock cannot be negative. In a production API, request and response DTOs should normally be separated from the persistence entity; that topic will be covered later.
using System.ComponentModel.DataAnnotations; public class Product { public int Id { get; set; } [Required] [MaxLength(120)] public string Name { get; set; } = string.Empty; [MaxLength(500)] public string? Description { get; set; } [Range(0.01, 1_000_000)] public decimal Price { get; set; } [Range(0, 1_000_000)] public int StockQuantity { get; set; } }
The DbContext represents the unit of work between the application and the database. We query and save products through DbSet<Product>.
using Microsoft.EntityFrameworkCore; public class AppDbContext : DbContext { public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { } public DbSet<Product> Products => Set<Product>(); }
Register the SQL Server provider and the context in dependency injection:
builder.Services.AddDbContext<AppDbContext>(options => options.UseSqlServer( builder.Configuration.GetConnectionString("DefaultConnection"))); builder.Services.AddControllers();
4. CRUD with ProductsController
The following controller contains the complete basic CRUD flow. AsNoTracking is used for read-only queries. During the PUT operation, a tracked entity is loaded so that EF Core can detect the property changes and persist them when SaveChangesAsync is called.
using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; [ApiController] [Route("api/[controller]")] public class ProductsController : ControllerBase { private readonly AppDbContext _db; public ProductsController(AppDbContext db) { _db = db; } [HttpGet] [ProducesResponseType(StatusCodes.Status200OK)] public async Task GetAll() { var products = await _db.Products .AsNoTracking() .OrderBy(p => p.Id) .ToListAsync(); return Ok(products); } [HttpGet("{id:int}")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status404NotFound)] public async Task GetById(int id) { var product = await _db.Products .AsNoTracking() .FirstOrDefaultAsync(p => p.Id == id); if (product is null) { return NotFound(); } return Ok(product); } [HttpPost] [ProducesResponseType(StatusCodes.Status201Created)] [ProducesResponseType(StatusCodes.Status400BadRequest)] public async Task Create(Product product) { if (product.Price <= 0) { return BadRequest("Price must be greater than zero."); } _db.Products.Add(product); await _db.SaveChangesAsync(); return CreatedAtAction( nameof(GetById), new { id = product.Id }, product); } [HttpPut("{id:int}")] [ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status400BadRequest)] [ProducesResponseType(StatusCodes.Status404NotFound)] public async Task Update(int id, Product request) { if (id != request.Id) { return BadRequest("The route id and body id must match."); } if (request.Price <= 0) { return BadRequest("Price must be greater than zero."); } var product = await _db.Products .FirstOrDefaultAsync(p => p.Id == id); if (product is null) { return NotFound(); } product.Name = request.Name; product.Description = request.Description; product.Price = request.Price; product.StockQuantity = request.StockQuantity; await _db.SaveChangesAsync(); return NoContent(); } [HttpDelete("{id:int}")] [ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status404NotFound)] public async Task Delete(int id) { var product = await _db.Products .FirstOrDefaultAsync(p => p.Id == id); if (product is null) { return NotFound(); } _db.Products.Remove(product); await _db.SaveChangesAsync(); return NoContent(); } }
Creation: POST and 201 Created
The POST action validates the request before adding it to the context. The [ApiController] attribute automatically participates in model validation based on data annotations. Explicit checks can be added for business rules that are not represented by simple attributes.
After the insert is saved, CreatedAtAction returns 201 and builds a Location header for the newly created resource. This gives the client a canonical URL that can be used to retrieve the product.
Reading: GET and 200 or 404
A collection endpoint should return 200 with an empty array when there are no products. An empty collection is not the same as a missing collection. For a request targeting one ID, however, the absence of that product is represented by 404. This distinction makes client behavior more predictable.
Updating: PUT and 204
The PUT action checks that the route ID and body ID match. Invalid input results in 400, while a missing product results in 404. If the update succeeds, the action returns 204 because the client does not need the complete Product representation again.
Deleting: DELETE and 204
The controller first loads the product so that it can distinguish “deleted” from “not found.” The entity is marked for deletion with Remove, and the database operation is performed by SaveChangesAsync. A successful delete returns 204 without an unnecessary body.
5. Request examples
Create a product with POST:
POST /api/products Content-Type: application/json { "name": "Mechanical Keyboard", "description": "Compact keyboard with tactile switches", "price": 89.90, "stockQuantity": 25 }
A successful response has status 201 and includes the created product. Update the product with PUT:
PUT /api/products/1 Content-Type: application/json { "id": 1, "name": "Mechanical Keyboard Pro", "description": "Updated model", "price": 109.90, "stockQuantity": 18 }
If the requirement is to change only the price, PATCH may be more appropriate. Such an endpoint should accept only explicitly permitted fields and should not overwrite omitted properties. Binding a PATCH body directly to an entity can accidentally allow clients to modify fields that should be server-controlled.
6. Common mistakes
- Returning 200 for everything: 201 is clearer for creation and 204 is clearer for successful operations without a response body.
- Returning an empty object for a missing resource: A 404 communicates the problem directly and avoids ambiguity for the client.
- Using PUT as an informal partial update: Missing fields can be replaced with defaults and cause data loss. Use PATCH or a dedicated update DTO for partial changes.
- Ignoring the route ID: Updating /products/5 with a body whose ID is 8 creates an ambiguous contract.
- Forgetting SaveChangesAsync: Add, Remove, and property changes are not persisted until the context saves them.
- Tracking read-only queries unnecessarily: AsNoTracking can reduce change-tracking overhead when the result will not be modified.
- Exposing the entity as the public contract: This can expose internal fields and create mass-assignment risks as the application grows.
7. Practice exercise
- Add the Product entity and AppDbContext to your project.
- Configure SQL Server, create a migration, and update the database.
- Add the ProductsController and run the five endpoints.
- Test GET collection, GET by ID, POST, PUT, and DELETE with Swagger or an HTTP client.
- Call GET, PUT, and DELETE with an unknown ID and verify the 404 responses.
- Send a negative price and a mismatched route/body ID, then verify the 400 responses.
- Inspect the Location header in the successful POST response and use it for a follow-up GET request.
Conclusion
In a professional REST API, method and status-code selection form part of the communication contract between the client and server. GET reads, POST creates, PUT replaces, PATCH partially updates, and DELETE removes resources. Entity Framework Core tracks changes and applies them to the database when SaveChangesAsync is called.
In this lesson, we built a complete CRUD flow for Product and used status codes that describe each result accurately. In the next stage, we will stop exposing persistence entities directly and introduce DTOs, stronger validation, and centralized error responses to make the API contract safer and easier to evolve.
Sources
- https://learn.microsoft.com/en-us/aspnet/core/web-api/action-return-types?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/aspnet/core/web-api/?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/ef/core/saving/basic
- https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.dbcontext.savechangesasync
- https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Methods
- https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status