.NET ProgrammingUnit 910 min read

Web APIs: REST, HTTP, JSON, ASP.NET Core, CRUD, Authentication

Unit 9 of .NET Programming covers how to build and consume Web APIs using ASP.NET Core, including RESTful principles, HTTP methods, JSON serialization, CRUD operations, authentication (JWT/OAuth), and real-world deployment scenarios like eSewa’s payment APIs or Daraz’s order management systems.

What is a Web API?

A Web API (Application Programming Interface) is a standardized way for applications to communicate over HTTP. Unlike traditional web pages, APIs exchange data in structured formats (usually JSON or XML) instead of rendering HTML. They follow REST (Representational State Transfer) principles, meaning they use HTTP methods (GET, POST, PUT, DELETE) to perform CRUD (Create, Read, Update, Delete) operations on resources.

Key Characteristics of Web APIs

  • Stateless: Each request from a client must contain all the information needed to process it.
  • Resource-based: APIs expose resources (e.g., /users, /orders) that clients interact with.
  • HTTP methods: Define actions (GET = fetch, POST = create, PUT = update, DELETE = remove).
  • JSON/XML: Data is exchanged in lightweight formats like JSON (preferred in modern APIs).

RESTful Architecture

REST is an architectural style for designing networked applications. It relies on:

  1. Resources: Identified by URIs (e.g., https://api.esewa.com.np/v3.0/payment).
  2. HTTP Methods: Standardized actions for resources.
  3. Statelessness: No client data is stored between requests.
  4. Representations: Resources are returned in formats like JSON.

HTTP Methods and Their Uses

Method Purpose Example Use Case
GET Retrieve data Fetch user profile (GET /users/123)
POST Create new data Submit a new order (POST /orders)
PUT Replace existing data Update user details (PUT /users/123)
PATCH Partially update data Change user email (PATCH /users/123)
DELETE Remove data Delete an order (DELETE /orders/456)

Building a Web API in ASP.NET Core

ASP.NET Core simplifies API development with built-in support for REST, JSON serialization, and dependency injection.

Step-by-Step: Creating a Simple API

  1. Create a new project:
    dotnet new webapi -n MyApiProject
    
  2. Define a model (e.g., Product.cs):
    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
    }
    
  3. Create a controller (ProductsController.cs):
    [Route("api/[controller]")]
    [ApiController]
    public class ProductsController : ControllerBase
    {
        private static List<Product> _products = new List<Product>
        {
            new Product { Id = 1, Name = "Laptop", Price = 50000 },
            new Product { Id = 2, Name = "Phone", Price = 20000 }
        };
    
        // GET: api/products
        [HttpGet]
        public IActionResult Get()
        {
            return Ok(_products);
        }
    
        // GET: api/products/5
        [HttpGet("{id}")]
        public IActionResult Get(int id)
        {
            var product = _products.FirstOrDefault(p => p.Id == id);
            if (product == null) return NotFound();
            return Ok(product);
        }
    
        // POST: api/products
        [HttpPost]
        public IActionResult Post([FromBody] Product product)
        {
            _products.Add(product);
            return CreatedAtAction(nameof(Get), new { id = product.Id }, product);
        }
    }
    
  4. Run the API:
    dotnet run
    
    Test endpoints using Postman or Swagger UI (enabled by default in ASP.NET Core).

Visual: API Request Flow

sequenceDiagram
    Client->>+API Server: GET /api/products (HTTP Request)
    API Server->>Database: Query Products
    Database-->>-API Server: Return Product List
    API Server-->>-Client: 200 OK (JSON Response)

JSON Serialization in .NET

JSON (JavaScript Object Notation) is the default format for ASP.NET Core APIs. The framework automatically serializes C# objects to JSON and vice versa.

Example: JSON Output for a Product

{
  "id": 1,
  "name": "Laptop",
  "price": 50000.00
}

How it works:

  • The [ApiController] attribute enables JSON serialization.
  • Use [FromBody] to bind JSON data to C# objects in POST/PUT requests.

CRUD Operations in APIs

Operation HTTP Method Example Endpoint Description
Create POST /api/products Add a new product to the database.
Read GET /api/products/1 Fetch a specific product.
Update PUT/PATCH /api/products/1 Modify an existing product.
Delete DELETE /api/products/1 Remove a product from the database.

Authentication and Authorization

APIs often require secure access. Common methods:

  1. API Keys: Simple but less secure (e.g., X-API-Key: abc123 in headers).
  2. JWT (JSON Web Tokens): Stateless tokens for authentication.
    • Client logs in (POST /api/auth/login) → receives a token.
    • Token is sent in the Authorization: Bearer <token> header for subsequent requests.
  3. OAuth 2.0: Delegated authorization (e.g., "Login with Google").

Example: JWT Authentication in ASP.NET Core

  1. Install the Microsoft.AspNetCore.Authentication.JwtBearer package.
  2. Configure in Program.cs:
    builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
        {
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidateLifetime = true,
                ValidIssuer = builder.Configuration["Jwt:Issuer"],
                ValidAudience = builder.Configuration["Jwt:Audience"],
                IssuerSigningKey = new SymmetricSecurityKey(
                    Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
            };
        });
    
  3. Protect controllers with [Authorize]:
    [Authorize]
    [Route("api/[controller]")]
    public class SecureController : ControllerBase { ... }
    

In the Real World

  1. eSewa API:

    • Uses RESTful endpoints (e.g., POST /v3.0/payment for transactions).
    • Returns JSON responses with payment status, transaction ID, and amounts.
    • How it works: When you pay a bill via eSewa, the app sends a POST request with your phone number, amount, and merchant ID. The API processes the payment and returns a confirmation or error in JSON.
  2. Daraz Order Management:

    • Daraz’s backend API handles CRUD operations for orders (e.g., GET /orders/12345 to track an order).
    • Uses JWT for seller/vendor authentication when updating order status.
    • Example: When a seller marks an order as "shipped," a PATCH request is sent to /orders/12345/status with the new status.
  3. Ncell’s Top-Up API:

    • Exposes endpoints like POST /topup to recharge mobile numbers.
    • Validates requests with API keys and returns JSON like:
      {
        "status": "success",
        "transactionId": "TXN12345",
        "balance": 500
      }
      

Consuming APIs in .NET

Use HttpClient to call APIs from your .NET applications.

Example: Fetching Data from a Public API

using System.Net.Http;
using System.Threading.Tasks;

public class ApiConsumer
{
    private readonly HttpClient _client;

    public ApiConsumer(HttpClient client)
    {
        _client = client;
    }

    public async Task<List<Product>> GetProductsAsync()
    {
        var response = await _client.GetAsync("https://api.example.com/products");
        response.EnsureSuccessStatusCode();
        var json = await response.Content.ReadAsStringAsync();
        return JsonSerializer.Deserialize<List<Product>>(json);
    }
}

Register HttpClient in Program.cs:

builder.Services.AddHttpClient<ApiConsumer>();

Error Handling in APIs

Return appropriate HTTP status codes for errors:

  • 400 Bad Request: Invalid input data.
  • 401 Unauthorized: Missing or invalid authentication.
  • 404 Not Found: Resource does not exist.
  • 500 Internal Server Error: Server-side failure.
RequestQueryError404 Not FoundClientAPIDatabase
Error flow diagram showing 404 response path with database failure.

Example: Custom Error Response

[HttpGet("{id}")]
public IActionResult Get(int id)
{
    var product = _products.FirstOrDefault(p => p.Id == id);
    if (product == null)
    {
        return NotFound(new { error = "Product not found" });
    }
    return Ok(product);
}

Exam Tip

  1. Understand REST principles: Know the difference between GET/POST/PUT/DELETE and when to use each.
  2. JSON serialization: Be able to convert between C# objects and JSON manually (e.g., serialize a Product class).
  3. ASP.NET Core setup: Remember key attributes like [ApiController], [Route], and [Authorize].
  4. Authentication: Explain how JWT works and where it’s stored (e.g., Authorization header).
  5. CRUD operations: Practice designing API endpoints for real-world scenarios (e.g., a bank loan system).
  6. Error handling: Always return meaningful HTTP status codes and error messages.

Visual: JWT Flow

sequenceDiagram
    Client->>+API: POST /login (username/password)
    API->>Database: Verify credentials
    Database-->>API: User exists?
    API->>Client: 200 OK (JWT Token)
    Client->>+API: GET /secure-data (Bearer Token)
    API->>Validator: Validate Token
    Validator-->>API: Valid
    API-->>Client: 200 OK (Data)

Visual: API Endpoint Design for a Bank Loan System

Resource GET POST PUT/PATCH DELETE
/loans List all loans Apply for a new loan Bulk update loans Delete a loan
/loans/{id} Get loan details N/A Update loan status Cancel a loan

Example Trace for POST /loans:

sequenceDiagram
    Client->>API: POST /loans (LoanApplication)
    API->>Validator: Check credit score
    Validator-->>API: Approved
    API->>Database: Save loan
    Database-->>API: Loan ID = 789
    API-->>Client: 201 Created (Loan ID: 789)

Based on the TU BIM syllabus for .NET Programming (IT275), unit 9.

Discussion

Loading…