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)
| Method | Purpose | Example |
|---|---|---|
GET | Read data | Get student list |
POST | Create data | Create new student |
PUT | Update data | Update student details |
DELETE | Delete data | Remove student |
Status Codes
| Code | Meaning | Example |
|---|---|---|
| 200 | OK | Request succeeded |
| 201 | Created | Resource created |
| 400 | Bad Request | Invalid input |
| 401 | Unauthorized | No auth token |
| 404 | Not Found | Student doesn't exist |
| 500 | Server Error | Database 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 studentsGET /api/students/101— Get student 101POST /api/students— Create studentPUT /api/students/101— Update student 101DELETE /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:
- Method: GET
- URL:
http://localhost:5000/api/students - Click Send
- 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
- Wrong HTTP method — POST for reading (should be GET)
- Ignoring status codes — Always return appropriate code
- No input validation — Accept any data
- 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
Have questions on your tech stack, ongoing projects, or need one-to-one training?