C#

n this tutorial we will use Json as sample database and will do CRUD operations.

We will learn about below HTTP verbs

  1. HttpPost -Create a record [C]
  2. HttpGet- Read a record [R]
  3. HttpPut- Update a record [U]
  4. HttpDelete -Delete a record [D]


Project Structure

Create .net core api project and final project structure as below

We will create below files

a. Inventory.json



javascript
[ { "Id": 1, "Name": "Sample Product 1", "Price": 23410.99, "Quantity": 10041 }, { "Id": 2, "Name": "Sample Product 2", "Price": 120.99, "Quantity": 150 }, { "Id": 3, "Name": "New Product", "Price": 15.99, "Quantity": 10 } ]

b. Inventory.cs (Model class)



javascript
public class Inventory { public int Id { get; set; } public string Name { get; set; } public decimal Price { get; set; } public int Quantity { get; set; } }

c. InventoryService.cs (This class contains all CRUD operations functions)


javascript
public class InventoryService { private const string JsonFilePath = "Inventory.json"; public string Fullpath = ""; public InventoryService() { } public List<Inventory> GetAllInventoryProducts() { string path =System.IO.Directory.GetCurrentDirectory()+"\\JSON"; Fullpath = Path.GetFullPath(Path.Combine(path, JsonFilePath)); if (!File.Exists(Fullpath)) { return new List<Inventory>(); } var jsonData = File.ReadAllText(Fullpath); return JsonConvert.DeserializeObject<List<Inventory>>(jsonData); } public Inventory GetInventroyProductById(int id) { var inventtoryProducts = GetAllInventoryProducts(); return inventtoryProducts.FirstOrDefault(p => p.Id == id); } public void AddProduct(Inventory product) { var Inventoryproducts = GetAllInventoryProducts(); product.Id = Inventoryproducts.Any() ? Inventoryproducts.Max(p => p.Id) + 1 : 1; // Assign new ID Inventoryproducts.Add(product); SaveProducts(Inventoryproducts); } public void UpdateProduct(Inventory product) { var products = GetAllInventoryProducts(); var existingProduct = products.FirstOrDefault(p => p.Id == product.Id); if (existingProduct != null) { existingProduct.Name = product.Name; existingProduct.Price = product.Price; existingProduct.Quantity = product.Quantity; SaveProducts(products); } } public void DeleteProduct(int id) { var products = GetAllInventoryProducts(); var productToRemove = products.FirstOrDefault(p => p.Id == id); if (productToRemove != null) { products.Remove(productToRemove); SaveProducts(products); } } private void SaveProducts(List<Inventory> products) { var jsonData = JsonConvert.SerializeObject(products, Newtonsoft.Json.Formatting.Indented); File.WriteAllText(Fullpath, jsonData); } }


d.Controller.cs (This contains all CRUD end points.)


javascript
[Route("api/[controller]")] [ApiController] public class InventoryController : Controller { private readonly InventoryService _inventoryProductService; public InventoryController() { _inventoryProductService = new InventoryService(); } // GET: api/products [HttpGet] public ActionResult<List<Inventory >> GetAllInventoryProducts() => _inventoryProductService.GetAllInventoryProducts(); // GET: api/products/5 [HttpGet("{id}")] public ActionResult<Inventory> GetProduct(int id) { var product = _inventoryProductService.GetInventroyProductById(id); if (product == null) { return NotFound(); } return product; } // POST: api/products [HttpPost] public ActionResult<Inventory> PostProduct(Inventory product) { _inventoryProductService.AddProduct(product); return CreatedAtAction(nameof(GetProduct), new { id = product.Id }, product); } // PUT: api/products/5 [HttpPut("{id}")] public IActionResult PutProduct(int id, Inventory product) { if (id != product.Id) { return BadRequest(); } _inventoryProductService.UpdateProduct(product); return NoContent(); } // DELETE: api/products/5 [HttpDelete("{id}")] public IActionResult DeleteProduct(int id) { _inventoryProductService.DeleteProduct(id); return NoContent(); } }


Reading JSON file, we have added below code to read json files and will deseralize into Inventory class.


javascript
public List<Inventory> GetAllInventoryProducts() { string path =System.IO.Directory.GetCurrentDirectory()+"\\JSON"; Fullpath = Path.GetFullPath(Path.Combine(path, JsonFilePath)); if (!File.Exists(Fullpath)) { return new List<Inventory>(); } var jsonData = File.ReadAllText(Fullpath); return JsonConvert.DeserializeObject<List<Inventory>>(jsonData); }

Running an application


1. HttpGet

When we executed get api and we get all records from json file in response.



Read by Id , we can also read by passing id, we have added another API which take id as input and gives result.


javascript
// GET: api/products/5 [HttpGet("{id}")] public ActionResult<Inventory> GetProduct(int id) { var product = _inventoryProductService.GetInventroyProductById(id); if (product == null) { return NotFound(); } return product; }



2. Http Post - We will add a record. we will create records as per below input. we need to Pass this Json as httprequest


javascript
{ "id": 99, "name": "devesh test product", "price": 110, "quantity": 23450 }

We posted this value and found 201 status code as below


Let's open Json file to verify record. and we can see its added into json file.


3. Http put - udpate record, we need to provide record id which we want to update and value by which we want to replace it.

Result. we will get status code 204 as per below.


Let's verify : we found Updated json file as below

4. Http delete. we will pass Id which we want to delete it.


javascript
// DELETE: api/products/5 [HttpDelete("{id}")] public IActionResult DeleteProduct(int id) { _inventoryProductService.DeleteProduct(id); return NoContent(); }




Input Id=3

Let's verify result, we can see record with id -3 is not in json file.



Let's verify result, we can see record with id -3 is not in json file.

We have learnt all important CRUD operations.

line

Copyrights © 2024 letsupdateskills All rights reserved