Understanding Common HTTP Verbs: A Guide to GET, POST, PUT, and More
Asharib Kamal
Sr. Full Stack Developer | Specializing in .NET Technologies | C# | Dot NET Core | Asp.NET MVC | Angular | SQL | Content Creator | Transforming Ideas into High-Impact Web Solutions | 7K + Followers
Introduction: In the realm of web development, HTTP (Hypertext Transfer Protocol) serves as the foundation for communication between clients and servers. Within this protocol, HTTP verbs, also known as HTTP methods, play a crucial role in specifying the desired action to be performed on a resource. In this article, we'll delve into the most common HTTP verbs—GET, POST, PUT, and others—exploring their functionalities, use cases, and implications in web development.
Key Points:
Certainly! Here are code examples demonstrating the usage of common HTTP verbs in a hypothetical web API built with ASP.NET Core:
[HttpGet]
public IActionResult Get()
{
// Retrieve resources from the server (e.g., list of items)
var items = _repository.GetAllItems();
return Ok(items); // Return 200 OK with the retrieved items
}
领英推荐
[HttpPost]
public IActionResult Post([FromBody] Item newItem)
{
// Create a new resource on the server (e.g., add a new item)
_repository.AddItem(newItem);
return CreatedAtAction(nameof(Get), new { id = newItem.Id }, newItem);
// Return 201 Created with the URI of the newly created resource
}
[HttpPut("{id}")]
public IActionResult Put(int id, [FromBody] Item updatedItem)
{
// Update an existing resource on the server (e.g., update item details)
_repository.UpdateItem(id, updatedItem);
return NoContent(); // Return 204 No Content
}
[HttpPatch("{id}")]
public IActionResult Patch(int id, [FromBody] JsonPatchDocument<Item> patchDocument)
{
// Apply partial updates to an existing resource (e.g., update specific fields)
var existingItem = _repository.GetItemById(id);
if (existingItem == null)
{
return NotFound(); // Return 404 Not Found if resource doesn't exist
}
patchDocument.ApplyTo(existingItem, ModelState);
if (!ModelState.IsValid)
{
return BadRequest(ModelState); // Return 400 Bad Request if patch is invalid
}
_repository.UpdateItem(id, existingItem);
return NoContent(); // Return 204 No Content
}
[HttpDelete("{id}")]
public IActionResult Delete(int id)
{
// Remove a resource from the server (e.g., delete an item)
var existingItem = _repository.GetItemById(id);
if (existingItem == null)
{
return NotFound(); // Return 404 Not Found if resource doesn't exist
}
_repository.DeleteItem(id);
return NoContent(); // Return 204 No Content
}
These examples demonstrate how to implement common HTTP verbs in an ASP.NET Core Web API controller. Each method corresponds to a specific HTTP verb and performs the corresponding action on the server
#HTTPVerbs #WebDevelopment #APIs #GET #POST #PUT #PATCH #DELETE #OPTIONS #Programming #TechEducation #LinkedInArticle ????