Build a REST API in ASP.NET Core: Complete Beginner's Guide

REST APIs power modern web applications, mobile apps, cloud services, and microservice architectures. Whether you're building a frontend, integrating third-party services, or creating a backend for mobile devices, understanding how to build a REST API is an essential skill for .NET developers.

In this tutorial, you'll learn how to create a REST API using ASP.NET Core, implement CRUD operations, validate requests, return proper HTTP status codes, and follow best practices for production-ready APIs.


Topics Covered
  • What is a REST API?
  • Creating an ASP.NET Core Web API project
  • Controllers and endpoints
  • GET, POST, PUT, DELETE operations
  • Data validation
  • HTTP status codes
  • Dependency Injection
  • Best practices

What Is a REST API?

REST (Representational State Transfer) is an architectural style used to build web services that communicate over HTTP.

Clients interact with resources using standard HTTP methods:

  • GET – Retrieve data
  • POST – Create data
  • PUT – Update data
  • DELETE – Remove data

Most modern APIs exchange data in JSON format.

Create a New ASP.NET Core Web API Project

Use the .NET CLI to create a new API project.


        dotnet new webapi -n ProductApi

        cd ProductApi
    

Run the application:


        dotnet run
    

By default, ASP.NET Core generates a sample WeatherForecast API.

Understanding Controllers

Controllers handle incoming HTTP requests and return responses.

Create a new controller named ProductsController.


        using Microsoft.AspNetCore.Mvc;

        namespace ProductApi.Controllers;

        [ApiController]
        [Route("api/[controller]")]
        public class ProductsController : ControllerBase
        {
        }
    

The route above maps requests to:


        /api/products
    

Create a Product Model

Create a simple model representing a product.


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

        public string Name { get; set; } = "";

        public decimal Price { get; set; }
        }
    

GET Endpoint

A GET endpoint returns data to clients.


        [HttpGet]
        public IActionResult GetProducts()
        {
        var products = new List<Product>
        {
        new Product
        {
        Id = 1,
        Name = "Laptop",
        Price = 999.99m
        }
        };

        return Ok(products);
        }
    

Example request:


        GET /api/products
    

GET by ID


        [HttpGet("{id}")]
        public IActionResult GetProduct(int id)
        {
        var product = new Product
        {
        Id = id,
        Name = "Laptop",
        Price = 999.99m
        };

        return Ok(product);
        }
    

Example request:


        GET /api/products/1
    

POST Endpoint

POST creates new resources.


        [HttpPost]
        public IActionResult CreateProduct(
        Product product)
        {
        product.Id = 100;

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

Example JSON request:


        {
        "name": "Keyboard",
        "price": 49.99
        }
    

PUT Endpoint

PUT updates existing resources.


        [HttpPut("{id}")]
        public IActionResult UpdateProduct(
        int id,
        Product product)
        {
        return NoContent();
        }
    

Successful updates commonly return:


        204 No Content
    

DELETE Endpoint


        [HttpDelete("{id}")]
        public IActionResult DeleteProduct(int id)
        {
        return NoContent();
        }
    

Example request:


        DELETE /api/products/1
    

Understanding HTTP Status Codes

Returning appropriate status codes helps API consumers understand results.

Status Code Meaning
200 OK Request succeeded
201 Created Resource created
204 No Content Successful request with no content
400 Bad Request Invalid request data
404 Not Found Resource does not exist
500 Internal Server Error Unexpected server failure

Adding Validation

Data validation prevents invalid information from entering your system.


        using System.ComponentModel.DataAnnotations;

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

        [Required]
        public string Name { get; set; } = "";

        [Range(0.01, 100000)]
        public decimal Price { get; set; }
        }
    

ASP.NET Core automatically validates models when using the ApiController attribute.

Dependency Injection

ASP.NET Core includes built-in Dependency Injection.

Instead of placing business logic inside controllers, services can be injected.


        public interface IProductService
        {
        IEnumerable<Product> GetAll();
        }
    

        builder.Services.AddScoped<IProductService,
        ProductService>();
    

Testing APIs with Swagger

ASP.NET Core includes Swagger support for documenting and testing APIs.


        builder.Services.AddEndpointsApiExplorer();

        builder.Services.AddSwaggerGen();
    

Swagger provides an interactive interface for testing endpoints directly from the browser.

Common Mistakes

  • Returning incorrect status codes.
  • Putting business logic in controllers.
  • Skipping input validation.
  • Ignoring exception handling.
  • Not documenting endpoints.
  • Using inconsistent route naming.

Best Practices

  • Use meaningful resource names.
  • Validate all incoming data.
  • Return proper HTTP status codes.
  • Keep controllers thin.
  • Use Dependency Injection.
  • Document APIs using Swagger.
  • Handle errors consistently.

Frequently Asked Questions

What is the difference between REST and SOAP?

REST is lightweight and commonly uses JSON, while SOAP is a protocol that often relies on XML and stricter standards.

Can ASP.NET Core build REST APIs?

Yes. ASP.NET Core is one of the most popular frameworks for building RESTful web services.

Should I use controllers or minimal APIs?

Controllers are often preferred for larger applications, while minimal APIs are useful for smaller projects.

What format do REST APIs usually return?

Most modern REST APIs return JSON responses.

Related Tutorials

Conclusion

Building REST APIs is one of the most valuable skills for modern .NET developers. ASP.NET Core provides a powerful framework for creating scalable, secure, and maintainable APIs.

By understanding controllers, CRUD operations, validation, HTTP status codes, dependency injection, and Swagger, you can build APIs that are easy to maintain and integrate with modern applications.