Shawn Ng'iela

Building Your First API - A Step-by-Step Guide using C#

Building Your First API - A Step-by-Step Guide using C#

APIs (Application Programming Interfaces) are the backbone of modern software development, enabling applications to communicate with each other.

Creating a RESTful API is a fundamental skill for modern developers. Whether you’re building a mobile app, a web application, or integrating systems, APIs are the backbone of communication between services.

In this guide, we’ll walk through building a simple RESTful API using C# and Visual Studio.

What is a RESTful API?

REST (Representational State Transfer) is an architectural style for designing networked applications. A RESTful API uses HTTP requests to perform CRUD (Create, Read, Update, Delete) operations on resources, which are typically represented in JSON or XML format.

Prerequisites

  • Visual Studio 2022 (Community edition is free)

  • .NET 6 or later (included with Visual Studio)

  • Basic knowledge of C# and HTTP concepts

Step 1: Create a New Project

  1. Open Visual Studio and click Create a new project.

  2. Select ASP.NET Core Web API and click Next.

  3. Name your project (e.g., FirstApi) and choose a location.

  4. Select .NET 6.0 (or later) as the framework.

  5. Click Create.

Visual Studio will generate a basic API template with a WeatherForecast controller .

Step 2: Understand the Project Structure

The generated project includes:

  • Controllers/ – Contains API endpoints (controllers handle HTTP requests).

  • Program.cs – Configures the application (middleware, services, etc.).

  • appsettings.json Configuration file (e.g., connection strings, logging).

Step 3: Create a Model

A model represents the data structure. Let’s create a simple Product model.

  1. Right-click the project → AddNew Folder → Name it Models .

  2. Right-click the Models folder → AddClass → Name it Product.cs .

  3. Define the model:

1
2
3
4
5
6
7
8
namespace FirstApi.Models;

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}

Step 4: Create a Controller

Controllers handle HTTP requests (GET, POST, PUT, DELETE).

  1. Right-click the Controllers folder → AddController.

  2. Select API Controller - Empty → Name it ProductsController.cs .

  3. Replace the code with:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
using Microsoft.AspNetCore.Mvc;
using FirstApi.Models;

namespace FirstApi.Controllers;

[Route("api/[controller]")]
[ApiController]
public class ProductsController : ControllerBase
{
    private static List<Product> products = new()
    {
        new Product { Id = 1, Name = "Laptop", Price = 999.99M },
        new Product { Id = 2, Name = "Phone", Price = 699.99M }
    };

    // GET: api/products
    [HttpGet]
    public ActionResult<IEnumerable<Product>> GetProducts()
    {
        return Ok(products);
    }

    // GET: api/products/1
    [HttpGet("{id}")]
    public ActionResult<Product> GetProduct(int id)
    {
        var product = products.Find(p => p.Id == id);
        if (product == null)
            return NotFound();
        return Ok(product);
    }

    // POST: api/products
    [HttpPost]
    public ActionResult<Product> AddProduct(Product product)
    {
        products.Add(product);
        return CreatedAtAction(nameof(GetProduct), new { id = product.Id }, product);
    }
}

Step 5: Run and Test the API

  1. Press F5 or click the Run button to start the API.

  2. Open a browser or Postman and test the endpoints:

    • GET https://localhost:5001/api/products – Retrieve all products.

    • GET https://localhost:5001/api/products/1 – Retrieve a single product.

    • POST https://localhost:5001/api/products – Add a new product (send JSON body).

Example POST request (JSON):

1
2
3
4
5
{
    "id": 3,
    "name": "Tablet",
    "price": 299.99
}

Step 6: Add More Functionality (Optional)

To make the API more robust, consider:

  • Data Validation (e.g., check for null values).

  • Database Integration (use Entity Framework Core).

  • Error Handling (global exception middleware).

  • Authentication (JWT, OAuth).

Conclusion

You’ve just built a basic RESTful API in C#! This is just the beginning — APIs can be extended with more features, security, and scalability.

Next Steps

  • Explore Swagger/OpenAPI for API documentation.

  • Learn about Dependency Injection in .NET.

  • Try integrating a database with Entity Framework Core.