How to Build An ASP.NET Core Web API: A Practical Beginner’s Tutorial

In this article, I’ll be demonstrating how to build an ASP.NET Core Web API. Web APIs are a crucial element of modern software development, as they allow applications to communicate with one another and enable the exchange of data. Having a solid understanding of how to build web APIs is essential for any software engineer.

That’s where ASP.NET Core comes in; it’s a flexible and powerful framework that provides developers with all the tools they need to build robust web APIs. In this tutorial, I’ll go over the basics of ASP.NET Core and walk you through creating a functional Web API. If you’re new to ASP.NET Core and web API development, this tutorial is a great starting point. Let’s get started!


Prerequisites to Build an ASP.NET Core Web API

Before diving into building an ASP.NET Core Web API, there are a few prerequisites that you need to have in place.

Required Software and Tools

Firstly, you’ll need a development environment with the following things installed. You’ll need to ensure you have the dotnet SDK installed so that you can develop using C#, which is a dotnet language. You’ll also want an integrated development environment (IDE) such as Visual Studio (Windows), Visual Studio Code (macOS, Linux, Windows), or Rider (cross-platform). I personally do all of my development in Visual Studio, but I have these two other articles to guide you through the setup for either of the Microsoft options:

You have options here, and I suggest you take some time to explore the different environments. If you just want to get going, leverage one of the above guides. However, as you get some downtime, make sure to explore the different tools you have available!

Recommended Knowledge and Experience

While this tutorial is designed for beginners, I recommend that you have some foundational knowledge in the following areas:

If you’re not up to speed on these yet, it might be a good opportunity to invest a bit of time before continuing on. But don’t sweat it – this is all a learning process anyway, and sometimes we learn better when we jump into the deep end. You can always follow up with these resources.

Additional Resources

If you are new to C# or OOP, you might find it helpful to review some introductory resources before continuing. While I provided some of my own resources, here are some additional useful links for further guidance:

By having these prerequisites in place, you’ll have everything needed to get started with this tutorial! Let’s see how to build an ASP.NET Core Web API. Let’s get to it!


Setting Up the Project to Build an ASP.NET Core Web API

To build a robust and scalable web API using ASP.NET Core, you first need to set up your project. Here’s a step-by-step guide on how to create your project from scratch:

  • First, open up Visual Studio and select “Create a new project.” This will open up the project creation wizard.
  • In the “Create new project” window, select “ASP.NET Core Web API” as the project template and click “Next”.
  • You’ll get to provide a name and a location for the project and solution, then click “Next”.
  • Finally, you’ll have some configuration settings for your project. If you’re unsure of any customizations, just leave the defaults and select “Create”.

You will now have an ASP.NET Core Web API solution to work with. While we’ll be looking at an MVC approach for our web API, you can watch this video to see how easy it is to create your project:

YouTube player

Initial Project State

Before you dive into coding, it’s important to become familiar with the project configuration files.

Two key files in an ASP.NET Core Web API project are the appsettings.json and Startup.cs files. The appsettings.json file is used to store configuration data that is sensitive, such as connection strings, and should never be checked into source control. The Startup.cs file contains the configuration code that is run when the application starts up, such as dependency injection setup and logging.

To set up the dependencies for your project, you can use NuGet. Right-click on the project in the Solution Explorer and select “Manage NuGet Packages.” From here, you can search for and install the necessary packages for your project, such as Entity Framework Core for data access and AutoMapper for object mapping. No need to add any for now though!


Defining the Data Model and Repository

When building a web API, one of the most crucial steps is defining the data model and repository. The data model represents the data structure that the API will work with while the repository provides access to that data structure while enforcing security and validation rules.

To create a basic data model example, you can start by defining a simple entity with some basic properties. For example, you could have a “Customer” entity with properties like “Id,” “Name,” “Phone Number,” and “Email.” It is important to keep the data model simple but also represent the kind of information that readers can realistically expect to work with.

// Data Model
public class Customer
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string PhoneNumber { get; set; }
    public string Email { get; set; }
}

Once you have defined the data model, the next step is to create a repository class that will provide access to the data model. Creating the repository entails implementing an interface that defines the behaviors and functionality that the repository must exhibit, such as adding and removing data from the data model.

Implementing the Repository

The implementation of the repository interface is where readers will learn how to provide the required functionality for the API. Using Entity Framework Core, readers can achieve this by creating “Create,” “Read,” “Update,” and “Delete” (CRUD) operations.

// Repository Interface
public interface ICustomerRepository
{
    IEnumerable<Customer> GetAll();
    Customer Get(int id);
    void Add(Customer customer);
    void Update(Customer customer);
    void Delete(int id);
}

// Repository Implementation
public class CustomerRepository : ICustomerRepository
{
    private readonly ApplicationDbContext _context;

    public CustomerRepository(ApplicationDbContext context)
    {
        _context = context;
    }

    public IEnumerable<Customer> GetAll() => _context.Customers.ToList();

    public Customer Get(int id) => _context.Customers.Find(id);

    public void Add(Customer customer)
    {
        _context.Customers.Add(customer);
        _context.SaveChanges();
    }

    public void Update(Customer customer)
    {
        _context.Customers.Update(customer);
        _context.SaveChanges();
    }

    public void Delete(int id)
    {
        var customer = _context.Customers.Find(id);
        if (customer != null)
        {
            _context.Customers.Remove(customer);
            _context.SaveChanges();
        }
    }
}

The four CRUD operations are carried out with SQL Data, and the appropriate syntax is implemented to complete the functions. They can then be used for later functionality of the API. With these CRUD operations in place, the repository can guarantee data integrity and ensure that it is accessible only by authorized users.


Building the API Endpoints

In this section, I’ll cover how to build API endpoints that allow clients to interact with our data model. We’ll use HTTP verbs (GET, POST, PUT, DELETE) to perform CRUD (Create, Read, Update, Delete) operations. I’ll also demonstrate how to use data validation attributes to ensure the quality of the input data.

We’ll start with an empty controller that uses our repository from earlier:

using Microsoft.AspNetCore.Mvc;

[Route("api/[controller]")]
[ApiController]
public class CustomerController : ControllerBase
{
    private readonly ICustomerRepository _repository;

    public CustomerController(ICustomerRepository repository)
    {
        _repository = repository;
    }
}

Retrieving Data using GET Requests

To retrieve data, we’ll use GET requests. Here are two examples, including getting a collection and getting a specific customer:

    // GET: api/customer
    [HttpGet("api/customer")]
    public IActionResult GetCustomers()
    {
        var customers = _repository.GetAll();
        return Ok(customers);
    }

    // GET: api/customer/5
    [HttpGet("api/customer/{id}")]
    public IActionResult GetCustomer(int id)
    {
        var customer = _repository.Get(id);
        if (customer == null)
        {
            return NotFound();
        }
        return Ok(customer);
    }

Creating and Updating Data using POST and PUT Requests

Next, we’ll look at how to create and update data using POST and PUT requests. We’ll be using POST in order to create a new customer and PUT to update an existing one. Here’s the example code:

    // POST: api/customer
    [HttpPost("api/customer")]
    public IActionResult PostCustomer([FromBody] Customer customer)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        _repository.Add(customer);
        return CreatedAtAction(nameof(GetCustomer), new { id = customer.Id }, customer);
    }

    // PUT: api/customer/5
    [HttpPut("api/customer/{id}")]
    public IActionResult PutCustomer(int id, [FromBody] Customer customer)
    {
        if (id != customer.Id || !ModelState.IsValid)
        {
            return BadRequest();
        }

        _repository.Update(customer);
        return NoContent();
    }

Deleting Data using DELETE Requests

To enable deleting data, we’ll use DELETE requests. Here is the endpoint we can use to delete a customer using our web API:

    // DELETE: api/customer/5
    [HttpDelete("api/customer/{id}")]
    public IActionResult DeleteCustomer(int id)
    {
        var customer = _repository.Get(id);
        if (customer == null)
        {
            return NotFound();
        }

        _repository.Delete(id);
        return NoContent();
    }

Overall, creating robust APIs is crucial for web application development, and being able to work with HTTP verbs for CRUD operations is key to achieving this. By using data validation attributes, you can ensure data quality, and by filtering, sorting, and paginating data, you can optimize performance. With these tools at your disposal, you’ll be well-equipped to create effective APIs.


Now You Know How to Build an ASP.NET Core Web API!

In this tutorial, I’ve demonstrated how to build an ASP.NET Core Web API from scratch. Together, we covered essential concepts such as setting up the project, defining the data model and repository, and building the API endpoints.

Some key takeaways from this tutorial include:

  • ASP.NET Core is a popular and modern framework used to build complex web applications and APIs.
  • A web API represents an essential part of software development, allowing different apps and platforms to communicate seamlessly.
  • I demonstrated how to set up the project after your prerequisites were installed.
  • We then explored code to define the data model and repository and build the API endpoints.

If you’re hungry for more, there are many resources available online to continue learning about ASP.NET Core and building web APIs. Here are some additional resources to help you get started:

  • .NET Core Documentation – Comprehensive documentation on .NET Core, including tutorials and guides on building web APIs.
  • Microsoft Learn – A platform that provides interactive learning resources on a wide range of topics and technologies, including ASP.NET Core.
  • Pluralsight – A popular online learning platform with many courses and tutorials on ASP.NET Core and C#.
  • Dometrain – Top-notch creators and software professionals creating dotnet-related courses.

I encourage you to take the lessons learned from this tutorial and apply them to your own projects! To continue learning more about software development and C#, subscribe to my Dev Leader Weekly newsletter and YouTube channel. Try building your ASP.NET Core web API today and let me know how it goes!

Affiliations:

These are products & services that I trust, use, and love. I get a kickback if you decide to use my links. There’s no pressure, but I only promote things that I like to use!

      • RackNerd: Cheap VPS hosting options that I love for low-resource usage!
      • Contabo: Alternative VPS hosting options with very affordable prices!
      • ConvertKit: This is the platform that I use for my newsletter!
      • SparkLoop: This service helps me add different value to my newsletter!
      • Opus Clip: This is what I use for help creating my short-form videos!
      • Newegg: For all sorts of computer components!
      • Bulk Supplements: For an enormous selection of health supplements!
      • Quora: I try to answer questions on Quora when folks request them of me!

    author avatar
    Nick Cosentino Principal Software Engineering Manager
    Principal Software Engineering Manager at Microsoft. Views are my own.

    Leave a Reply