2. Basic API Development

  1. Basic API Development

2.1 Creating Your First Controller

[Route(“api/[controller]”)][ApiController]public class PlatformsController : ControllerBase{    [HttpGet]    public ActionResult<IEnumerable> GetPlatforms()    {        return Ok(new[] { “Windows”, “Linux”, “Docker” });    }} Controller Base Classes: Controller vs ControllerBase (API-specific) [ApiController] Attribute: Automatic model validation, binding source inference Why ControllerBase: No view support needed for APIs 2.2 Understanding Routing Convention-based routing (older, not used here) Attribute-based routing (modern approach):

[Route(“api/[controller]”)]  // Class level: /api/platforms[HttpGet("{id}")]             // Method level: /api/platforms/5[HttpGet("{id}/commands")]    // Nested: /api/platforms/5/commands Route Parameters: {id} - required parameter {id?} - optional parameter {id:int} - constrained to integer Route Precedence: More specific routes first 2.3 HTTP Verbs and RESTful Conventions Verb Purpose Idempotent Safe Example GET Retrieve Yes Yes Get platform by ID POST Create No No Create new platform PUT Full Update Yes No Replace platform PATCH Partial Update Yes No Update platform name DELETE Remove Yes No Delete platform Teaching Point: Explain idempotency with examples DELETE same resource twice = same result (404 after first) POST same data twice = two resources created (not idempotent) 2.4 Returning Data with ActionResult

// Old way (less type safety)public ActionResult GetPlatform(int id){    return Ok(platform);  // What type is returned?}// New way (better for documentation and type safety)public ActionResult GetPlatform(int id){    var platform = _repo.GetById(id);    if (platform == null)        return NotFound();        return Ok(platform);  // Compiler knows it’s PlatformReadDto} Status Code Helpers: Ok(data) - 200 Created(uri, data) - 201 CreatedAtRoute(routeName, routeValues, data) - 201 with Location header NoContent() - 204 BadRequest(errors) - 400 NotFound() - 404 2.5 Testing with HTTP Files Creating CommandAPI.http:

@baseUrl = https://localhost:7213@apiKey = your-api-key-here### Get all platformsGET {{baseUrl}}/api/platformsAccept: application/json### Get platform by IDGET {{baseUrl}}/api/platforms/1Accept: application/json### Create new platformPOST {{baseUrl}}/api/platformsContent-Type: application/jsonx-api-key: {{apiKey}}{  “platformName”: “Kubernetes”}### Update platformPUT {{baseUrl}}/api/platforms/1Content-Type: application/jsonx-api-key: {{apiKey}}{  “platformName”: “Kubernetes Updated”}### Delete platformDELETE {{baseUrl}}/api/platforms/1x-api-key: {{apiKey}} Benefits: Version controlled, shareable, no external tools needed Variables: Reusable base URLs and tokens VS Code Integration: REST Client extensio