Q: Write a simple REST API using .NET Core?

Step 1: Setting up the Project

Start by ensuring you have the .NET SDK installed. You can download it from the .NET official website. Once installed, open a command prompt and run the following command to create a new project:

dotnet new webapi -n SimpleApi

This command creates a new directory called SimpleApi with a basic template for a Web API.

Step 2: Exploring the Project Structure

Once your project is created, navigate into the directory:

cd SimpleApi

In the project, you’ll find the following key elements:

  • Controllers folder: This is where your API controllers will reside. Each controller handles incoming HTTP requests.
  • Models folder (Create it if not present): This will store your data models.
  • Program.cs: The entry point of the application. This is where the web host is configured.

Step 3: Creating a Model

Models define the data structure. For this example, let’s create a simple model for a Product. Create a new Product.cs file inside the Models folder:

namespace SimpleApi.Models { public class Product { public int Id { get; set; } public string Name { get; set; } public decimal Price { get; set; } } }

This Product model has three properties: Id, Name, and Price.

Step 4: Creating the Controller

Now, let’s create a controller to handle HTTP requests regarding products. Create a new file named ProductsController.cs inside the Controllers folder:

using Microsoft.AspNetCore.Mvc; using SimpleApi.Models; using System.Collections.Generic; using System.Linq; namespace SimpleApi.Controllers { [Route("api/[controller]")] [ApiController] public class ProductsController : ControllerBase { private static List<Product> products = new List<Product> { new Product { Id = 1, Name = "Product 1", Price = 9.99m }, new Product { Id = 2, Name = "Product 2", Price = 19.99m } }; [HttpGet] public ActionResult<IEnumerable<Product>> GetProducts() { return Ok(products); } [HttpGet("{id}")] public ActionResult<Product> GetProduct(int id) { var product = products.FirstOrDefault(p => p.Id == id); if (product == null) { return NotFound(); } return Ok(product); } [HttpPost] public ActionResult<Product> CreateProduct(Product product) { product.Id = products.Max(p => p.Id) + 1; // Simple ID assignment products.Add(product); return CreatedAtAction(nameof(GetProduct), new { id = product.Id }, product); } [HttpPut("{id}")] public IActionResult UpdateProduct(int id, Product product) { var existingProduct = products.FirstOrDefault(p => p.Id == id); if (existingProduct == null) { return NotFound(); } existingProduct.Name = product.Name; existingProduct.Price = product.Price; return NoContent(); } [HttpDelete("{id}")] public IActionResult DeleteProduct(int id) { var product = products.FirstOrDefault(p => p.Id == id); if (product == null) { return NotFound(); } products.Remove(product); return NoContent(); } } }

Step 5: Understanding the Controller Actions

Let's break down the controller methods:

  • GetProducts: This action returns the list of all products with a GET request to /api/products.
  • GetProduct: This action retrieves a specific product by ID with a GET to /api/products/{id}.
  • CreateProduct: This action creates a new product with a POST request to /api/products. It generates an ID for the product and adds it to the list.
  • UpdateProduct: This action updates an existing product with a PUT request to /api/products/{id}. It checks if the product exists and modifies it if found.
  • DeleteProduct: This action removes a product with a DELETE request to /api/products/{id}. If the product exists, it’s removed from the list.

Step 6: Running the API

To run your API, go back to the terminal and execute:

dotnet run

You should see output indicating the server is running. By default, the API will be hosted at http://localhost:5000.

Step 7: Testing the API

You can test your API using tools like Postman or curl. Here’s how to test some endpoints:

  • Get all products: Send a GET request to http://localhost:5000/api/products.
  • Get a single product: Send a GET request to http://localhost:5000/api/products/1.
  • Create a product: Send a POST request with a JSON body to http://localhost:5000/api/products.
  • Update a product: Send a PUT request to http://localhost:5000/api/products/1 with a JSON body.
  • Delete a product: Send a DELETE request to http://localhost:5000/api/products/1.

Conclusion

This simple REST API allows you to perform basic CRUD operations on a product list using .NET Core. You can extend this API with additional features like database integration, authentication, and error handling to meet your needs. Take your time to explore these enhancements as you grow more comfortable with the framework.

Share now!