Introduction:
HTTP (Hypertext Transfer Protocol) is a communication protocol that allows client and server applications to exchange data over the Internet. When developing a RESTful API with .NET Core Web API, it is essential to understand the different HTTP verbs and status codes that are used in HTTP requests and responses. In this blog post, we will discuss the basics of HTTP verbs and status codes in .NET Core Web API, their usage, and some common examples.
HTTP Verbs:
HTTP verbs (also known as HTTP methods) are used to specify the type of action that should be performed on a resource. The most common HTTP verbs are:
- GET: Used to retrieve a resource from the server.
- POST: Used to create a new resource on the server.
- PUT: Used to update an existing resource on the server.
- DELETE: Used to delete a resource from the server.
- PATCH: Used to partially update an existing resource on the server.
Here are some examples of how HTTP verbs are used in real-time scenarios:
GET:
The GET method is used to retrieve a resource from the server. For example, when you visit a website, your browser sends a GET request to the server to retrieve the web page. In a .NET Core Web API, you can use the [HttpGet] attribute to map a controller action to a GET request.
[HttpGet]
public IActionResult Get()
{
// Retrieve a list of resources
var resources = _repository.GetResources();
// Return the list of resources in the response body
return Ok(resources);
}
GET with parameter:
The GET method can also be used to retrieve a specific resource by passing an identifier as a parameter. In a .NET Core Web API, you can use the [HttpGet(“{id}”)] attribute to map a controller action to a GET request with a parameter.
[HttpGet("{id}")]
public IActionResult Get(int id)
{
// Retrieve the resource with the specified id
var resource = _repository.GetResourceById(id);
// Return the resource in the response body
return Ok(resource);
}
POST: The POST method is used to create a new resource on the server. For example, when you submit a form on a website, your browser sends a POST request to the server with the data from the form. In a .NET Core Web API, you can use the [HttpPost] attribute to map a controller action to a POST request.
[HttpPost]
public IActionResult Post([FromBody] Resource resource)
{
// Create a new resource in the database
_repository.AddResource(resource);
// Return the newly created resource in the response body
return CreatedAtAction(nameof(Get), new { id = resource.Id }, resource);
}
PUT:
The PUT method is used to update an existing resource on the server. For example, when you edit a record in a database, your application might send a PUT request to update the record. In a .NET Core Web API, you can use the [HttpPut] attribute to map a controller action to a PUT request.
[HttpPut("{id}")]
public IActionResult Put(int id, [FromBody] Resource resource)
{
// Update the resource in the database
_repository.UpdateResource(id, resource);
// Return the updated resource in the response body
return Ok(resource);
}
DELETE:
The DELETE method is used to delete a resource from the server. For example, when you delete a file from your computer, your operating system sends a DELETE request to remove the file. In a .NET Core Web API, you can use the [HttpDelete] attribute to map a controller action to a DELETE request.
[HttpDelete("{id}")]
public IActionResult Delete(int id)
{
// Delete the resource from the database
_repository.DeleteResource(id);
// Return a 204 No Content response to indicate success
return NoContent();
}
PATCH:
The PATCH method is used to partially update an existing resource on the server. For example, if you have a user profile with multiple fields, a PATCH request could be used to update only one field without affecting the others. In a .NET Core Web API, you can use the [HttpPatch] attribute to map a controller action to a PATCH request.
[HttpPatch("{id}")]
public IActionResult Patch(int id, [FromBody] JsonPatchDocument<Resource> patchDocument)
{
// Retrieve the resource with the specified id
var resource = _repository.GetResourceById(id);
// Apply the patch to the resource
patchDocument.ApplyTo(resource, ModelState);
// Validate the updated resource
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
// Update the resource in the database
_repository.UpdateResource(id, resource);
// Return the updated resource in the response body
return Ok(resource);
}
These are just a few examples of how HTTP verbs can be used in a .NET Core Web API. By understanding these verbs and their associated actions, you can build powerful and flexible RESTful APIs that can be used in a variety of applications.
Status Codes:
HTTP status codes are used to indicate the status of an HTTP request or response. Some of the most common HTTP status codes are:
- 201 Created: This status code is returned when a resource has been successfully created on the server. It is typically returned in response to a successful POST request.
- 202 Accepted: This status code is returned when a request has been accepted for processing, but the server has not yet completed the requested operation. This can be used for long-running tasks that take some time to complete.
- 400 Bad Request: This status code is returned when the server is unable to process a request due to a client error, such as invalid parameters or missing required fields.
- 401 Unauthorized: This status code is returned when a client attempts to access a protected resource without providing valid authentication credentials.
- 403 Forbidden: This status code is returned when a client attempts to access a resource for which they do not have the necessary permissions.
- 404 Not Found: This status code is returned when the server is unable to find the requested resource.
- 500 Internal Server Error: This status code is returned when the server encounters an error while processing a request. This can indicate a problem with the server-side code or with the server itself.
It’s important to choose the appropriate status code for each response in order to provide clear and informative feedback to the client.
Here are some common HTTP status codes for each HTTP verb:
- GET:
- 200 OK: The request was successful and the response contains the requested resource.
- 404 Not Found: The requested resource was not found on the server.
- POST:
- 201 Created: The resource was successfully created on the server.
- 400 Bad Request: The request was invalid or missing the required parameters.
- PUT:
- 200 OK: The resource was successfully updated on the server.
- 404 Not Found: The requested resource was not found on the server.
- DELETE:
- 204 No Content: The resource was successfully deleted from the server.
- 404 Not Found: The requested resource was not found on the server.
- PATCH:
- 200 OK: The resource was successfully updated on the server.
- 400 Bad Request: The request was invalid or missing the required parameters.
- 404 Not Found: The requested resource was not found on the server.
Check out other topics that might interest you.
- Automating API Requests with C# and Azure Functions using HttpTrigger.
- Building an Azure Function with Input Binding to Read and Process Excel Files from Azure Blob Storage
- A Step-by-Step Guide to Enabling Diagnostics Logging for Azure App Service Web Apps | AZ-204
Application Source Code @ LearnSmartCoding GitHub
Conclusion
In this blog post, we have discussed the basics of HTTP verbs and status codes in .NET Core Web API. Understanding these concepts is crucial when building RESTful APIs, as they allow us to communicate with the server in a standardized and consistent manner. By using the appropriate HTTP verbs and status codes, we can provide clear and informative feedback to our clients and ensure that our API is reliable and easy to use.