Creating Your First Web API

Intermediate 25 min read Lesson 3 of 10

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.

Hands-on Practice Lab

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!

1
Create the Project

Open Visual Studio again and create a new project.

Search for ASP.NET Core Web API. Name it StudentManagerAPI. Keep the default settings and click Create.
2
Create the Student Model

We need a C# class to define what a "Student" looks like (the data).

Right-click the project name → Add → Class... Name it 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; }
    }
}
3
Create the Controller

This is where we write the REST endpoints.

Right-click the Controllers folder → Add → Controller... → Select API Controller - Empty. Name it 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.

Test 1: GET Request

Click on GET /api/students → Try it out → Execute.

Result: You will see Ali and Sarah's data returned as JSON!

Test 2: POST Request

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!

Incredible job! You just built a real RESTful API. You wrote a C# class, used REST routing, and tested it live in your browser.
Test Your Knowledge - Take Quiz