---
title: "How do you create an API in ASP.NET Core?"  
description: "How do you create an API in ASP.NET Core?"  
author: "Utpal Vishwas"  
published: 2025-05-20  
updated: 2026-06-08  
canonical: https://www.mindstick.com/forum/161641/how-do-you-create-an-api-in-asp-dot-net-core  
category: "c#"  
tags: ["c#", "api(s)"]  
reading_time: 4 minutes  

---

# How do you create an API in ASP.NET Core?

1. Use `[ApiController]` and `[Route("api/[controller]")]` [attributes](https://www.mindstick.com/articles/13105/2-attributes-that-make-your-odoo-ecommerce-theme-productive-and-engaging) on controllers.
2. Use `[HttpGet]`, `[HttpPost]`, etc., to [define](https://yourviews.mindstick.com/audio/1110/lifestyles-choices-that-define-our-lives) actions.

## Replies

### Reply by ICSM Computer

Creating an API in ASP.NET Core is straightforward thanks to the built-in Web API template. Here's a step-by-step guide.

## Step 1: Create a New ASP.NET Core Web API Project

Using the .NET CLI:

```plaintext
# Create a new Web API project
dotnet new webapi -n ProductApi

# Navigate to the project directory
cd ProductApi
```

Or in Visual Studio:

- Create a new project.
- Select **ASP.NET Core Web API**.
- Enter the project name.
- Click **Create**.

## Step 2: Examine the Project Structure

A typical project structure looks like:

```plaintext
ProductApi
│
├── Controllers
├── Program.cs
├── appsettings.json
├── Properties
└── ProductApi.csproj
```

## Step 3: Create a Model

Create a `Models` folder and add a `Product` class.

```cs
namespace ProductApi.Models;

public class Product
{
    // Product identifier
    public int Id { get; set; }

    // Product name
    public string Name { get; set; } = string.Empty;

    // Product price
    public decimal Price { get; set; }
}
```

## Step 4: Create a Controller

Inside the `Controllers` folder, create `ProductsController.cs`.

```cs
using Microsoft.AspNetCore.Mvc;
using ProductApi.Models;

namespace ProductApi.Controllers;

[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
    // Sample in-memory data
    private static readonly List<Product> Products =
    [
        new Product
        {
            Id = 1,
            Name = "Laptop",
            Price = 50000
        },
        new Product
        {
            Id = 2,
            Name = "Mouse",
            Price = 1000
        }
    ];

    // GET: api/products
    [HttpGet]
    public IActionResult GetAll()
    {
        return Ok(Products);
    }
}
```

## Step 5: Configure Services

In .NET 6+ (`Program.cs`):

```cs
var builder = WebApplication.CreateBuilder(args);

// Add controller services
builder.Services.AddControllers();

// Add Swagger services
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Enable Swagger
app.UseSwagger();
app.UseSwaggerUI();

// Map controllers
app.MapControllers();

app.Run();
```

## Step 6: Run the API

```plaintext
dotnet run
```

Example output:

```plaintext
Now listening on:
https://localhost:7001
http://localhost:5001
```

## Step 7: Test the API

Open:

```plaintext
https://localhost:7001/swagger
```

Swagger UI allows you to test endpoints directly from the browser.

Example response from `GET /api/products`:

```plaintext
[
  {
    "id": 1,
    "name": "Laptop",
    "price": 50000
  },
  {
    "id": 2,
    "name": "Mouse",
    "price": 1000
  }
]
```

## Step 8: Add a POST Endpoint

```cs
[HttpPost]
public IActionResult Create(Product product)
{
    // Generate a new Id
    product.Id = Products.Max(p => p.Id) + 1;

    // Add product to collection
    Products.Add(product);

    return CreatedAtAction(
        nameof(GetById),
        new { id = product.Id },
        product);
}
```

Add a GET by Id endpoint:

```cs
[HttpGet("{id}")]
public IActionResult GetById(int id)
{
    // Find product by Id
    var product = Products.FirstOrDefault(p => p.Id == id);

    if (product == null)
        return NotFound();

    return Ok(product);
}
```

## Step 9: Add PUT Endpoint

```cs
[HttpPut("{id}")]
public IActionResult Update(int id, Product updatedProduct)
{
    // Find existing product
    var product = Products.FirstOrDefault(p => p.Id == id);

    if (product == null)
        return NotFound();

    // Update values
    product.Name = updatedProduct.Name;
    product.Price = updatedProduct.Price;

    return NoContent();
}
```

## Step 10: Add DELETE Endpoint

```cs
[HttpDelete("{id}")]
public IActionResult Delete(int id)
{
    // Find product
    var product = Products.FirstOrDefault(p => p.Id == id);

    if (product == null)
        return NotFound();

    // Remove product
    Products.Remove(product);

    return NoContent();
}
```

## Complete CRUD Endpoints

| HTTP Method | Endpoint | Description |
| --- | --- | --- |
| GET | `/api/products` | Get all products |
| GET | `/api/products/{id}` | Get product by ID |
| POST | `/api/products` | Create product |
| PUT | `/api/products/{id}` | Update product |
| DELETE | `/api/products/{id}` | Delete product |

## Next Steps for Production Applications

After creating a basic API, you'll typically add:

- **Entity Framework Core** for database access.
- **Dependency Injection** for services and repositories.
- **Validation** using Data Annotations or FluentValidation.
- **Authentication & Authorization** using JWT tokens.
- **Logging** with the built-in logging framework.
- **Exception Handling Middleware**.
- **API Versioning**.
- **Unit Testing** with xUnit and Moq.
- **Docker Support**.
- **CI/CD Pipelines** using GitHub Actions or Azure DevOps.

This is the standard approach for building RESTful APIs in modern ASP.NET Core applications.


---

Original Source: https://www.mindstick.com/forum/161641/how-do-you-create-an-api-in-asp-dot-net-core

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
