Creating Your First Web API
Now that you understand the theory of API and REST, it's time to open Visual Studio and build a real one using ASP.NET Core. Don't worry, Visual Studio does most of the heavy lifting for us!
Step 1: Create the Project
Open Visual Studio, click "Create a new project", and search for ASP.NET Core Web API. Name it MyFirstApi.
Visual Studio will generate a complete, working project for you. It includes a default "Weather Forecast" example. This is a brilliant way to see exactly how an API works before you write your own code.
Step 2: Understanding the "Controller"
In the world of ASP.NET Core, an API is built using something called a Controller.
Think of a Controller as the Waiter we talked about in Lesson 1. It's just a C# class that listens for requests and responds to them.
Open the WeatherForecastController.cs file inside the Controllers folder. You will see this:
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
// ... code that generates fake weather data ...
}
}
Let's translate this into Plain English:
[ApiController]
This is a label that tells Visual Studio: "Hey! This class is an API, not a normal website." It automatically turns your C# data into JSON text so other apps can read it.
[Route("[controller]")]
This sets the URL address for the API. Because your class is named WeatherForecastController, ASP.NET Core is smart enough to drop the word "Controller" and create this URL: https://localhost:1234/WeatherForecast
[HttpGet]
This is the REST rule in action! It tells the API: "Only run this C# method if the user sends a GET request". (GET means "give me data").
Step 3: Run Your API!
Press F5 on your keyboard to run the app. A browser window will open with a tool called Swagger UI.
Swagger is an automatic testing tool. It reads your code and creates a beautiful webpage to test your API without writing any front-end code!
Click on GET /WeatherForecast → Try it out → Execute. You will see the JSON data appear right there on the screen.
Awesome!
You just ran a REST API. Your browser was the Client (Waiter), it sent a GET request, and the C# server responded with JSON data.
Build Your Own: Student Manager API
Enough looking at examples. Let's create a brand new API from scratch to manage students. No database needed!
Create the Project
Open Visual Studio again and create a new project.
StudentManagerAPI. Keep the default settings and click Create.
Create the Student Model
We need a C# class to define what a "Student" looks like (the data).
Student.cs. Paste this inside:
namespace StudentManagerAPI
{
public class Student
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public int Age { get; set; }
}
}
Create the Controller
This is where we write the REST endpoints.
StudentsController.cs.
Delete the default code and paste this. Notice the REST rules we learned—the URL is a Noun (students) and we use HTTP Verbs (GET, POST):
using Microsoft.AspNetCore.Mvc;
namespace StudentManagerAPI.Controllers
{
[Route("api/[controller]")] // Noun in URL: "students"
[ApiController]
public class StudentsController : ControllerBase
{
// A fake in-memory database
private static List<Student> _students = new List<Student>
{
new Student { Id = 1, Name = "Ali", Age = 20 },
new Student { Id = 2, Name = "Sarah", Age = 22 }
};
// GET: api/students
[HttpGet]
public IActionResult GetStudents()
{
return Ok(_students); // Returns 200 OK + JSON list
}
// POST: api/students
[HttpPost]
public IActionResult AddStudent(Student newStudent)
{
newStudent.Id = _students.Count + 1;
_students.Add(newStudent);
return CreatedAtAction(nameof(GetStudents), newStudent);
}
}
}
Run and Test Your API
Press F5 to run it. Swagger UI will open.
Click on GET /api/students → Try it out → Execute.
Result: You will see Ali and Sarah's data returned as JSON!
Click on POST /api/students → Try it out.
In the Request Body box, paste this JSON:
{
"name": "John",
"age": 25
}
Click Execute.
Result: The API will return a 201 Created status and show you John's new ID!