8.3 C
New York
Thursday, March 20, 2025

Easy methods to implement idempotent APIs in ASP.NET Core



Now let’s get began with our implementation. For our instance, we’ll use a easy buying cart software.

Create the mannequin courses

Within the challenge we created earlier, create the next courses within the Fashions folder.


public class Product
{
   public int Product_Id { get; set; }
   public string Product_Code { get; set; }
   public string Product_Name { get; set; }
   public double Product_Price { get; set; }
}
public class Order
{
   public int Order_Id { get; set; }
   public Record Merchandise { get; set; }
}
public class KeyStore
{
   public string Key { get; set; }
   public DateTime Expiry { get; set; }
}

Whereas the Product and Order courses are sometimes utilized in a ShoppingCart software, the KeyStore class is used right here to retailer our idempotency keys. On this implementation, we’ll save these keys within the database (dbContext). Naturally, you can change the implementation to retailer the keys within the cache or some other knowledge retailer.

Create the controller class

Proper-click on the Controllers folder within the Answer Explorer Window and create an API controller known as OrderController. Now, enter the next motion methodology within the OrderController class. This methodology creates a brand new order.


[HttpPost]
public IActionResult CreateOrder([FromBody] Order order, [FromHeader(Name = "X-Idempotency_Key")] string key)
{
    if (string.IsNullOrEmpty(key))
    {
        return BadRequest("Idempotency key's required.");
    }
    if (_dbContext.KeyStore.FirstOrDefault(okay => okay.Key == key)!= null)
    {
        var existingItem = _dbContext.Orders.FirstOrDefault(o => o.Order_Id == order.Order_Id);
        return Battle(new { message = "Request has already been processed.", merchandise = existingItem });
    }
    _dbContext.KeyStore.Add(new KeyStore {Key = key, Expiry = DateTime.Now.AddDays(7)});
    _dbContext.Add(order);
    _dbContext.SaveChanges();
    return Okay(order.Order_Id);
}

Look at the code above. An idempotency key’s generated on the consumer aspect and handed within the request header. This key will likely be utilized by the server to make sure that repeated calls to the identical motion methodology won’t create duplicate data within the database. In different phrases, if the bottom line is already current within the KeyStore, then the request for creation of the useful resource will likely be ignored. The presence of the important thing within the KeyStore signifies that the request was already processed earlier.

Takeaways

By embracing idempotency, you may construct APIs which are strong, dependable, and fault-tolerant. Idempotent APIs are notably necessary and useful in distributed techniques, the place community points may result in massive numbers of retried requests from the consumer aspect. That mentioned, it is best to all the time validate enter knowledge to make sure knowledge consistency earlier than storing knowledge within the database.



Supply hyperlink

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles