Blog
03 · Web API & Network ProtocolsPart 0220 min read

How to Communicate with APIs: HTTP Packet Anatomy, JSON, JWT Authentication, and Client Code

A deep dive into client-server API communication: raw HTTP Request/Response headers, JWT (Header.Payload.Signature) Bearer tokens, solving CORS policies, building a TypeScript/Next.js API client, and avoiding socket exhaustion in C# with IHttpClientFactory.

Emirhan Uluksar
Emirhan Uluksar

Founder & Principal Software Architect · Digital HAT

1 views
How to Communicate with APIs: HTTP Packet Anatomy, JSON, JWT Authentication, and Client Code

In the previous lesson, we built and launched our ASP.NET Core RESTful Web API server. Now we turn to one of the most fundamental engineering tasks you will perform every day in production: establishing secure, resilient, and type-safe communication with a Web API from a frontend application (React / Next.js) and from backend C# microservices!

Many developers lose hours debugging 401 Unauthorized, 403 Forbidden, 415 Unsupported Media Type, or browser CORS Policy Blocked errors because they treat HTTP libraries as a black box without inspecting the raw packet traveling across the wire. In this tutorial, we will X-ray raw HTTP request and response packets line by line, dissect the cryptographic structure of a JWT (JSON Web Token), build a production-grade TypeScript / Next.js API service layer, implement a resilient C# Typed HttpClient (IHttpClientFactory) that prevents TCP socket exhaustion, and configure CORS properly in ASP.NET Core.

What You Will Master in This Guide:
1. Line-by-line X-ray of a raw HTTP/2 Request and Response Packet over the wire.
2. The HTTP Error Status Code Diagnostic Table (400, 401, 403, 404, 415, 422, 429, 500).
3. How JWT (JSON Web Token) works under the hood: Header.Payload.Signature and the Authorization: Bearer header.
4. Where to organize API client files in a Next.js / TypeScript project (full code for src/services/api-client.ts and products.service.ts).
5. Why instantiating new HttpClient() in C# (.NET) causes catastrophic Socket Exhaustion, and how to configure IHttpClientFactory with SocketsHttpHandler.
6. Why CORS (Cross-Origin Resource Sharing) errors happen in browsers and how to configure ASP.NET Core CORS policies securely.
Client-Server API Communication over HTTPS with JSON and JWT Bearer Tokens

1. Line-by-Line X-Ray of an HTTP Request and Response Packet

When your browser or backend service invokes an API endpoint, the exact text frame transmitted over the TLS-encrypted TCP connection looks like this:

POST /api/products HTTP/2                          <-- 1. REQUEST LINE: Verb (POST) + Path (/api/products) + Protocol
Host: api.dgtalhat.com                             <-- 2. TARGET SERVER HOSTNAME
Content-Type: application/json; charset=utf-8      <-- 3. PAYLOAD MEDIA TYPE (Omitting this triggers HTTP 415!)
Accept: application/json                           <-- 4. EXPECTED RESPONSE FORMAT
Accept-Language: en-US                             <-- 5. REQUESTED LOCALE (For localized content & messages)
X-Correlation-Id: 4a8b9c12-0011-4e22-9988-776655   <-- 6. DISTRIBUTED TRACING CORRELATION ID
Authorization: Bearer eyJhbGciOiJIUzI1NiIs...      <-- 7. CREDENTIAL HEADER (JWT Token - Omitting triggers HTTP 401!)
                                                   <-- 8. BLANK LINE (CRLF separator between Headers and Body)
{                                                  <-- 9. REQUEST BODY (UTF-8 JSON Payload)
  "name": "DHRevora Cloud POS Enterprise License",
  "sku": "DH-REV-01",
  "unitPrice": 9500.00,
  "stockQuantity": 100
}

Once Kestrel processes the command and persists the record in PostgreSQL, the server sends back the following HTTP Response Packet:

HTTP/2 201 Created                                 <-- 1. STATUS LINE: Protocol + Status Code (201 Created)
Date: Sun, 29 Mar 2026 11:20:00 GMT                <-- 2. SERVER UTC TIMESTAMP
Content-Type: application/json; charset=utf-8      <-- 3. RESPONSE PAYLOAD MEDIA TYPE
Location: https://api.dgtalhat.com/api/products/9c1a... <-- 4. CANONICAL URI OF THE NEWLY CREATED RESOURCE
X-RateLimit-Remaining: 59                          <-- 5. REMAINING QUOTA IN CURRENT WINDOW
                                                   <-- 6. BLANK LINE
{                                                  <-- 7. RESPONSE BODY (JSON)
  "id": "9c1a4b22-7d33-4a11-8e99-112233445566",
  "name": "DHRevora Cloud POS Enterprise License",
  "sku": "DH-REV-01",
  "unitPrice": 9500.00,
  "stockQuantity": 100,
  "isInStock": true,
  "createdAt": "2026-03-29T11:20:00+00:00"
}

2. Production HTTP Error Code Diagnostic Table

Whenever an API call fails, inspect the HTTP status code first—it immediately tells you whether the bug resides in the client request or the backend server:

Status Code Standard Name Root Cause & Engineering Fix
400 Bad Request Malformed JSON syntax or failed DTO validation (e.g., missing required field or wrong property name).
401 Unauthorized Authentication failed: Missing Authorization: Bearer <token> header, invalid signature, or expired JWT (exp).
403 Forbidden Authorization denied: Your JWT is valid (the server knows who you are), but your account lacks the required role or permission claim.
404 Not Found Misspelled endpoint route (e.g., /api/product instead of /api/products) or the requested GUID does not exist in PostgreSQL.
415 Unsupported Media Type You sent a JSON body in a POST/PUT call but forgot to attach the Content-Type: application/json header.
422 Unprocessable Entity Syntactically valid JSON that violated a domain business rule (e.g., attempting to deduct more stock than available).
429 Too Many Requests Rate limit exceeded. Read the Retry-After response header and back off before retrying.
500 / 502 Internal Server / Bad Gateway Your client request is valid; the backend threw an unhandled exception or lost connectivity to downstream infrastructure.

3. How Does JWT (JSON Web Token) Authentication Work Cryptographically?

When a user authenticates via POST /api/auth/login, the server verifies their password hash (Argon2id / BCrypt) and issues a digitally signed JWT (JSON Web Token) consisting of three dot-separated Base64Url segments: HEADER.PAYLOAD.SIGNATURE

// 1. HEADER (Base64Url-encoded):
{
  "alg": "HS256",
  "typ": "JWT"
}

// 2. PAYLOAD / CLAIMS (Base64Url-encoded — NOT ENCRYPTED, READABLE BY ANYONE!):
{
  "sub": "f47ac10b-58cc-4372-a567-0e02b2c3d479",
  "email": "architect@dgtalhat.com",
  "role": "EnterpriseAdmin",
  "tenant_id": "dh-holding-01",
  "iat": 1774780000,
  "exp": 1774783600
}

// 3. SIGNATURE (Computed using the Server's 256-bit Secret Key):
HMACSHA256(
  base64UrlEncode(header) + "." + base64UrlEncode(payload),
  SERVER_256_BIT_SECRET_KEY
)
Critical Security Warning:
1. The second segment of a JWT (Payload) is merely Base64Url-encoded, not encrypted. Anyone who intercepts or inspects the token can decode its JSON claims. Never store passwords, raw secrets, or sensitive PII inside a JWT payload!
2. What prevents tampering? The third segment: the Cryptographic Signature! If a malicious user modifies "role": "User" to "role": "EnterpriseAdmin" in the payload, the HMAC-SHA256 signature no longer matches. ASP.NET Core's AuthenticationMiddleware detects the signature mismatch in microseconds and rejects the request with 401 Unauthorized!

4. Building an Enterprise API Client Layer in Next.js / TypeScript

In a professional Next.js or React codebase, we never scatter raw fetch(...) calls across UI components. Instead, we create a centralized, type-safe service layer under src/services/ with automatic locale headers, Bearer token injection, timeout protection, and structured error handling:

my-nextjs-app/
└── src/
    ├── services/
    │   ├── api-client.ts        # Core HTTP/JSON/JWT/Timeout & ApiError wrapper
    │   └── products.service.ts  # Strongly-typed getAll, getById, create, updatePrice, remove methods
    └── app/
        └── products/
            └── page.tsx         # Next.js page consuming productsService

Let us write both production TypeScript files in full:

// 1. File Path: src/services/api-client.ts
const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || "https://api.dgtalhat.com/api";

export class ApiError extends Error {
  constructor(
    public readonly status: number,
    message: string,
    public readonly details?: unknown
  ) {
    super(message);
    this.name = "ApiError";
  }
}

export interface ApiRequestOptions extends RequestInit {
  token?: string;
  locale?: "tr" | "en" | "de";
  timeoutMs?: number;
}

export async function apiRequest<TResponse>(
  endpoint: string,
  options: ApiRequestOptions = {}
): Promise<TResponse> {
  const { token, locale = "en", timeoutMs = 10000, headers, ...restOptions } = options;

  const requestHeaders: Record<string, string> = {
    "Accept": "application/json",
    "Accept-Language": locale,
    "X-Language-Code": locale,
    ...(options.body ? { "Content-Type": "application/json; charset=utf-8" } : {}),
    ...(token ? { "Authorization": `Bearer ${token}` } : {}),
    ...(headers as Record<string, string>),
  };

  const response = await fetch(`${API_BASE_URL}${endpoint}`, {
    ...restOptions,
    headers: requestHeaders,
    // Automatically abort hung connections after 10 seconds:
    signal: options.signal ?? AbortSignal.timeout(timeoutMs),
  });

  if (!response.ok) {
    const errorPayload = await response.json().catch(() => null);
    const message =
      errorPayload?.detail ||
      errorPayload?.message ||
      `API request failed with HTTP ${response.status}`;
    throw new ApiError(response.status, message, errorPayload);
  }

  // Return null for HTTP 204 No Content responses:
  if (response.status === 204) {
    return null as TResponse;
  }

  return (await response.json()) as TResponse;
}
// 2. File Path: src/services/products.service.ts
import { apiRequest } from "./api-client";

export interface ProductDto {
  id: string;
  name: string;
  sku: string;
  unitPrice: number;
  stockQuantity: number;
  isInStock: boolean;
  createdAt: string;
}

export interface CreateProductInput {
  name: string;
  sku: string;
  unitPrice: number;
  stockQuantity: number;
}

export const productsService = {
  getAll: (locale: "tr" | "en" | "de" = "en") =>
    apiRequest<ProductDto[]>("/products", { method: "GET", locale }),

  getById: (id: string, locale: "tr" | "en" | "de" = "en") =>
    apiRequest<ProductDto>(`/products/${id}`, { method: "GET", locale }),

  create: (input: CreateProductInput, jwtToken: string) =>
    apiRequest<ProductDto>("/products", {
      method: "POST",
      token: jwtToken,
      body: JSON.stringify(input),
    }),

  updatePrice: (id: string, newUnitPrice: number, jwtToken: string) =>
    apiRequest<ProductDto>(`/products/${id}/price`, {
      method: "PUT",
      token: jwtToken,
      body: JSON.stringify({ newUnitPrice }),
    }),

  remove: (id: string, jwtToken: string) =>
    apiRequest<void>(`/products/${id}`, {
      method: "DELETE",
      token: jwtToken,
    }),
};

5. Calling External APIs from C# (.NET) Backends Using IHttpClientFactory

When a C# backend service needs to call an external REST API (such as an ERP gateway, payment processor, or e-invoicing authority), the single most destructive mistake developers make is writing using var client = new HttpClient(); inside a method!

Why is new HttpClient() dangerous? Disposing an HttpClient instance does not immediately release the underlying OS TCP socket—the socket remains in the TIME_WAIT state for up to 240 seconds. Under heavy traffic, your server rapidly runs out of ephemeral outbound ports (Socket Exhaustion) and crashes. Conversely, keeping a naive single static HttpClient forever ignores DNS changes when the target server rotates its IP address.

The proper enterprise solution in .NET is registering a Typed HttpClient (AddHttpClient) managed by IHttpClientFactory with a rotating PooledConnectionLifetime:

// 1. File Path: src/DigitalHat.Commerce.Infrastructure/ExternalClients/ErpAccountingClient.cs
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;

namespace DigitalHat.Commerce.Infrastructure.ExternalClients;

public record ErpInvoiceSyncRequest(Guid OrderId, string CustomerTaxNumber, decimal GrandTotal);
public record ErpInvoiceSyncResponse(bool Success, string OfficialInvoiceNumber, DateTimeOffset IssuedAt);

public class ErpAccountingClient
{
    private readonly HttpClient _httpClient;
    private readonly ILogger<ErpAccountingClient> _logger;

    // HttpClient is injected from IHttpClientFactory backed by a managed socket pool:
    public ErpAccountingClient(HttpClient httpClient, ILogger<ErpAccountingClient> logger)
    {
        _httpClient = httpClient;
        _logger = logger;
    }

    public async Task<ErpInvoiceSyncResponse?> SyncInvoiceAsync(
        ErpInvoiceSyncRequest payload,
        string apiToken,
        CancellationToken ct = default)
    {
        using var request = new HttpRequestMessage(HttpMethod.Post, "v1/invoices/sync");
        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", apiToken);
        request.Headers.Add("X-Idempotency-Key", payload.OrderId.ToString());
        request.Content = JsonContent.Create(payload); // Serializes C# record to UTF-8 JSON

        _logger.LogInformation("Starting ERP invoice synchronization for OrderId={OrderId}", payload.OrderId);

        using var response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, ct);

        if (!response.IsSuccessStatusCode)
        {
            string errorBody = await response.Content.ReadAsStringAsync(ct);
            _logger.LogError("ERP API Failure ({StatusCode}): {ErrorBody}", (int)response.StatusCode, errorBody);
            response.EnsureSuccessStatusCode();
        }

        return await response.Content.ReadFromJsonAsync<ErpInvoiceSyncResponse>(cancellationToken: ct);
    }
}

// 2. Registration in Program.cs (.NET automatically manages socket pooling and DNS rotation!):
builder.Services.AddHttpClient<ErpAccountingClient>(client =>
{
    client.BaseAddress = new Uri("https://erp-gateway.example-enterprise.com/");
    client.Timeout = TimeSpan.FromSeconds(15);
    client.DefaultRequestHeaders.Add("Accept", "application/json");
    client.DefaultRequestHeaders.Add("User-Agent", "DigitalHat-Commerce-Backend/1.0");
})
.ConfigurePrimaryHttpMessageHandler(() => new SocketsHttpHandler
{
    // Recycle pooled TCP connections every 5 minutes to respect DNS updates:
    PooledConnectionLifetime = TimeSpan.FromMinutes(5)
});

6. What Causes CORS (Cross-Origin Resource Sharing) Errors and How to Fix Them

When your frontend runs at https://dgtalhat.com (or http://localhost:3000) and your Web API runs at https://api.dgtalhat.com (or http://localhost:5000), the browser enforces the Same-Origin Policy. Before sending any cross-origin POST request with an Authorization header, the browser automatically dispatches a Preflight OPTIONS request asking your server whether that origin is explicitly whitelisted.

To allow your frontend domains securely in ASP.NET Core, register a named CORS policy in Program.cs:

// Configuring an Explicit CORS Policy in Program.cs:
builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowedFrontendOrigins", policy =>
    {
        policy.WithOrigins(
                "https://dgtalhat.com",
                "https://www.dgtalhat.com",
                "http://localhost:3000")
              .AllowAnyHeader()
              .AllowAnyMethod()
              .AllowCredentials();
    });
});

var app = builder.Build();

// IMPORTANT: UseCors must be placed BEFORE UseAuthentication, UseAuthorization, and MapControllers!
app.UseCors("AllowedFrontendOrigins");
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();

7. Next Lesson: What Is Rate Limiting? Protecting APIs from Overload and Bot Attacks

We have built our RESTful Web API and connected both our Next.js frontend and C# backend services over HTTPS with JWT authentication. In Part 3 of this series, we will build the defensive shield that stops credential-stuffing bots, scrapers, and traffic floods: Rate Limiting Algorithms and ASP.NET Core Middleware Implementation!

Did you find this engineering guide helpful?

Give it a like or share it with your team and network.

1 views
Share This Guide: