C#

HTTP Code for CRUD Operations

We do Insert, Update, Delete, Modify data requests so let's see what code we need to return from API.

Suppose we found operation success in CRUD operations then we return

2xx - Success Responses

1. 200 OK  

 Used for fetching  or reading data from api

Example ( GET /GetData

[HttpGet(Name = "Read")] public async Task<IActionResult> GetData() { return Ok("Read is susscufull"); }


).



2. 201 Created

Suppose we requested to Insert data to API and request is successful then we should return 201 status from api.


/// <summary> /// Returns 201 Created /// </summary> [HttpPost("created")] public IActionResult InsertItem([FromBody] string value) { if (string.IsNullOrWhiteSpace(value)) { return BadRequest(new { error = "Value cannot be empty." }); } int id = _items.Count + 1; _items.Add(id, value); return CreatedAtAction(nameof(GetItem), new { id }, new { id, value }); }





3. 202 Accepted

The HTTP 202 Accepted successful response status code indicates that a request has been accepted for processing, but processing has not been completed or may not have started.

Suppose user submitted one request for data for report generation we can use this status code and informed user like requested accepted but we will process later.


/// <summary> /// Returns 202 Accepted /// </summary> [HttpPost("accepted")] public IActionResult ProcessAsyncTask() { return Accepted(new { message = "Request accepted and being processed." }); }


4. 204 No Content

The request was successful, but there’s no data to return.

Example when we delete something and in that case we do not have anything to return then we can use.


/// <summary> /// Returns 204 No Content /// </summary> [HttpDelete("nocontent/{id}")] public IActionResult DeleteItem(int id) { if (_items.Remove(id)) { return NoContent(); } return NotFound(new { error = "Item not found." }); }



4xx - Client Errors

These indicate that the request was invalid or cannot be fulfilled by the server.

1. 401 Unauthorized

We can use this status when user going to Login and he does not have permission to access then  we can send back with unauthorize status code.


[HttpGet("Login")] public IActionResult Login(string userid, string password) { if(userid!="devesh1234" && password!="test9090") return Unauthorized(new { error = "Authorization required." }); else { // add logic to navigate to enter in application } }


2. 404 Not Found

The requested resource was not found.

Suppose user requested for particular data and its not found in database then we can return back with this status code.


[HttpGet("notfound/{id}")] public IActionResult GetItem(int id) { if (!_items.TryGetValue(id, out var value)) { return NotFound(new { error = "Item not found." }); } return Ok(new { id, value }); }


3. 400 Bad Request

we can return with bad request if user sent some payload and if it is not good or incorrect values it have then we can respond back with BAD request


[HttpGet("badrequest")] public IActionResult GetBadRequest(string input) { if(!input.Contains("Type")) return BadRequest(new { error = "Invalid request." }); else // add logic }


4. 429 Too Many Requests

We can use this code in case of protecting api with too many request sent with in period.

Example : In irctc railway tickets , we are not allowed more than 1 ticket in tatkal period


/// <summary> /// Returns 429 Too Many Requests /// </summary> [HttpGet("toomanyrequests")] public IActionResult GetTooManyRequests() { return StatusCode(429, new { error = "Too many requests. Please try again later." }); }

 

5. 403 Forbidden

The 403 Forbidden status code means the server understood the request, but refuses to authorize it. Unlike 401 Unauthorized, where authentication is missing or invalid, 403 Forbidden occurs when the user is authenticated but lacks necessary permissions.


[Authorize] [HttpGet("admin-data")] public IActionResult GetAdminData() { var userRole = User.FindFirst("role")?.Value; if (userRole != "Admin") { return Forbid(); // 403 Forbidden } return Ok(new { data = "Admin-only data" }); }




6. 413 Payload Too Large

413 Payload Too Large occurs when a client sends a request body that exceeds the server's configured size limit. This typically happens when


  1. A file upload is too large.
  2. A JSON payload is too big.
  3. A client sends too much data in an API request.

Examples: 

1. File Upload Limits :  The server only allows files up to 5MB, but the user uploads a 50MB file.

 2. Large JSON Payloads: A bulk insert operation tries to send 10,000 records in one request.

We need to configure file size at startup.cs


var builder = WebApplication.CreateBuilder(args); // Configure max request body size (e.g., 5MB) builder.Services.Configure<IISServerOptions>(options => { options.MaxRequestBodySize = 5 * 1024 * 1024; // 5MB }); builder.Services.Configure<KestrelServerOptions>(options => { options.Limits.MaxRequestBodySize = 5 * 1024 * 1024; // 5MB }); var app = builder.Build(); app.UseRouting(); app.MapControllers(); app.Run();

Now  If a client tries to upload a file larger than 5MB, the server will return:

HTTP/1.1 413 Payload Too Large



5xx - Server Errors

These indicate that the server failed to fulfill a valid request.

1. 500 Internal Server Error

Basic Example - Unhandled Exception



[HttpGet("server-error")] public IActionResult GetServerError() { int x = 0; int result = 10 / x; // Division by zero return Ok(result); }


Result: 

HTTP/1.1 500 Internal Server Error


Another example: 

Suppose user is fetching data from database and some issue happen from DB side like out of memory or connection loss then we will get HTTP code 500 error

2. 503 Service Unavailable : 

suppose server is on scheduled maintenance downtime and in that period of time we try to reach then we will get this error.

3. 504 Gateway Timeout

The server did not receive a timely response from an upstream server.

Suppose we are doing API to API communication then in case we did not get response with in time specified then we will get 504 gateway error.

Another reason High Network Latency

Network issues between the proxy server and the upstream service can cause delays in the communication, resulting in a timeout.

Example: A service in one data center is trying to communicate with a service located in another region, and network congestion causes delays.


Thanks, Happy coding and learning 



line

Copyrights © 2024 letsupdateskills All rights reserved