Introduction to ASP.NET Core Web APIs
ASP.NET Core Web APIs are a powerful framework for building HTTP services that can be consumed by a broad range of clients, including browsers, mobile apps, and other backend services. This tutorial will guide you through the essential steps and concepts involved in creating your first ASP.NET Core Web API.
Why Build Web APIs?
- Decoupling: Separate frontend and backend logic.
- Scalability: Build services that can handle increasing load.
- Interoperability: Enable communication between different applications and platforms.
- Microservices: Foundation for building modern microservice architectures.
Prerequisites
Before you begin, ensure you have the following installed:
- .NET SDK (latest version recommended)
- A code editor like Visual Studio Code, Visual Studio, or JetBrains Rider
Setting Up Your Project
Let's start by creating a new ASP.NET Core Web API project.
1. Create the Project
Open your terminal or command prompt and run the following command:
dotnet new webapi -o MyFirstApi
cd MyFirstApi
This command creates a new directory named MyFirstApi
with a basic Web API project structure.
2. Explore the Project Structure
The generated project includes:
Controllers/
: Contains your API controllers.appsettings.json
: Configuration file.Program.cs
: Entry point for your application.
Creating Your First API Endpoint
We'll create a simple endpoint to return a list of items.
1. Define a Model
Create a new folder named Models
and add a new C# file named Item.cs
:
namespace MyFirstApi.Models
{
public class Item
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
}
2. Create a Controller
In the Controllers
folder, create a new C# file named ItemsController.cs
:
using Microsoft.AspNetCore.Mvc;
using MyFirstApi.Models;
using System.Collections.Generic;
using System.Linq;
namespace MyFirstApi.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class ItemsController : ControllerBase
{
private static List<Item> _items = new List<Item>
{
new Item { Id = 1, Name = "Laptop", Description = "A portable computer." },
new Item { Id = 2, Name = "Keyboard", Description = "An input device." },
new Item { Id = 3, Name = "Mouse", Description = "A pointing device." }
};
[HttpGet]
public ActionResult<IEnumerable<Item>> GetAllItems()
{
return Ok(_items);
}
[HttpGet("{id}", Name = "GetItemById")]
public ActionResult<Item> GetItem(int id)
{
var item = _items.FirstOrDefault(i => i.Id == id);
if (item == null)
{
return NotFound();
}
return Ok(item);
}
}
}
The [ApiController]
attribute enables API-specific behaviors.
The [Route("api/[controller]")]
attribute defines the base route for this controller, which will be /api/Items
.
The [HttpGet]
attribute indicates that the GetAllItems
method handles HTTP GET requests.
The [HttpGet("{id}", Name = "GetItemById")]
attribute defines a GET endpoint that accepts an ID parameter.
Running Your API
To run your API, execute the following command in your terminal:
dotnet run
Your API will typically be hosted on https://localhost:5001
or http://localhost:5000
.
Testing the Endpoint
You can test your endpoints using a tool like Postman or by navigating to the URLs in your browser:
- Get all items:
https://localhost:5001/api/items
- Get item by ID (e.g., ID 1):
https://localhost:5001/api/items/1
Next Steps
This is just the beginning. You can further explore:
- Implementing HTTP POST, PUT, and DELETE operations.
- Working with databases using Entity Framework Core.
- Implementing authentication and authorization.
- Adding input validation.
- Using dependency injection effectively.
- Deploying your API to Azure or other cloud platforms.