Skip to main content

ASP.NET Core Web API Fundamentals

Level: Intermediate

ℹ️ What You'll Learn
  • REST principle: Use HTTP methods (GET/POST/PUT/DELETE) on resources (/students, not /getStudents)
  • GET method: Retrieve data (GET /students → list of students, GET /students/101 → one student)
  • POST method: Create new resource (POST /students with student data → returns 201 Created with new ID)
  • PUT method: Update entire resource (PUT /students/101 with new data → replaces student 101)
  • DELETE method: Remove resource (DELETE /students/101 → removes student, returns 204 No Content)
  • PATCH method: Partial update (PATCH /students/101 with partial data → updates only sent fields)
  • Status codes: 200 (OK), 201 (Created), 204 (No Content), 400 (Bad Request), 401 (Unauthorized), 404 (Not Found), 500 (Server Error)
  • JSON format: Standard data exchange format with key-value pairs (id, name, className fields)
  • Request/response cycle: Client sends HTTP request → Server processes → Server sends response with status + data
  • HTTP headers: Content-Type (application/json), Authorization (Bearer token), Accept (what format client wants)
  • Stateless principle: Each request independent, server doesn't remember previous requests
  • API design for SMS: GET /students, POST /students, GET /students/{id}, PUT /students/{id}, DELETE /students/{id}
  • REST vs RPC: REST uses HTTP methods on resources, RPC calls functions (not REST style)
  • Swagger/OpenAPI: Auto-generated documentation showing all endpoints, methods, parameters, responses

What is a REST API?

REST = REpresentational State Transfer

API = Application Programming Interface

Allows client (frontend) → server (backend) communication via HTTP.

SMS Example:

  • Frontend requests: GET all students
  • Backend responds: JSON list of students

HTTP Methods (CRUD)

MethodPurposeExample
GETRead dataGet student list
POSTCreate dataCreate new student
PUTUpdate dataUpdate student details
DELETEDelete dataRemove student

Status Codes

CodeMeaningExample
200OKRequest succeeded
201CreatedResource created
400Bad RequestInvalid input
401UnauthorizedNo auth token
404Not FoundStudent doesn't exist
500Server ErrorDatabase error

API Request Flow

Client Server
│ │
│─ GET /api/students ───────> │
│ (with headers, auth) │
│ │ Query database
│ │ Build JSON
│<─ 200 OK + JSON Response ── │
│ [{ id, name, ... }] │

Create First Endpoint

File: Controllers/StudentsController.cs

using Microsoft.AspNetCore.Mvc;
using SMS.Core.Models;
using SMS.Core.Services;

namespace SMS.Api.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class StudentsController : ControllerBase
{
private readonly IStudentService _service;

public StudentsController(IStudentService service)
{
_service = service;
}

[HttpGet]
public async Task<ActionResult<List<Student>>> GetStudents()
{
var students = await _service.GetStudentsAsync();
return Ok(students); // 200 OK
}

[HttpGet("{id}")]
public async Task<ActionResult<Student>> GetStudent(int id)
{
var student = await _service.GetStudentAsync(id);
if (student == null)
return NotFound(); // 404 Not Found

return Ok(student); // 200 OK
}

[HttpPost]
public async Task<ActionResult<Student>> CreateStudent([FromBody] Student student)
{
await _service.CreateStudentAsync(student);
return CreatedAtAction(nameof(GetStudent), new { id = student.Id }, student); // 201 Created
}

[HttpPut("{id}")]
public async Task<ActionResult> UpdateStudent(int id, [FromBody] Student student)
{
student.Id = id;
await _service.UpdateStudentAsync(student);
return NoContent(); // 204 No Content
}

[HttpDelete("{id}")]
public async Task<ActionResult> DeleteStudent(int id)
{
await _service.DeleteStudentAsync(id);
return NoContent(); // 204 No Content
}
}
}

Key Concepts

Routes:

  • GET /api/students — List all students
  • GET /api/students/101 — Get student 101
  • POST /api/students — Create student
  • PUT /api/students/101 — Update student 101
  • DELETE /api/students/101 — Delete student 101

HTTP Headers:

Content-Type: application/json
Authorization: Bearer <token>
Accept: application/json

Request Body (JSON):

{
"name": "Ravi Kumar",
"rollNumber": "SMS-2024-001",
"className": "10-A",
"status": "Active"
}

Response Body (JSON):

{
"id": 101,
"name": "Ravi Kumar",
"rollNumber": "SMS-2024-001",
"className": "10-A",
"status": "Active"
}

Testing API

Use Postman:

  1. Method: GET
  2. URL: http://localhost:5000/api/students
  3. Click Send
  4. See response

Or curl:

curl http://localhost:5000/api/students

Architecture

Client (React, Angular, Mobile)

├─ HTTP Request

API Gateway

Controllers (Route requests)

Services (Business logic)

Data Layer (Database)

Layered approach = separation of concerns.

Key Takeaways

  • REST API = HTTP-based communication
  • CRUD = GET, POST, PUT, DELETE
  • Status codes = indicate result
  • JSON = data format
  • ASP.NET Core = fast, scalable API framework
💡 API Design Tip

Use consistent naming. /api/students not /api/student_list or /api/get_students.

⚠️ Common Mistakes
  1. Wrong HTTP method — POST for reading (should be GET)
  2. Ignoring status codes — Always return appropriate code
  3. No input validation — Accept any data
  4. Hardcoding values — Use dependency injection
🤖Use AI to Learn Faster

Use ChatGPT, Claude, or Copilot to go deeper on Web API Fundamentals. Try these prompts:

  • "What's the difference between GET and POST?"
  • "When do I return 404 vs 400?"
  • "How do I structure API endpoints?"
  • "Quiz me on Web API basics"

💡 Tip: After reading this article, paste your own code into AI and ask "What could go wrong here and why?" — fastest way to find edge cases and deepen understanding.

nexcoding.in