Blog
03 · Web API & NetzwerkprotokolleTeil 0220 Min. Lesezeit

Wie kommuniziert man mit APIs? HTTP-Pakete, JSON, JWT-Authentifizierung und Client-Code

Vom exakten Aufbau eines HTTP-Requests über JWT-Bearer-Token und CORS-Konfiguration bis hin zu produktionsreifen API-Clients in TypeScript/Next.js und C# (IHttpClientFactory).

Emirhan Uluksar
Emirhan Uluksar

Gründer & Leitender Softwarearchitekt · Digital HAT

1 Aufrufe
Wie kommuniziert man mit APIs? HTTP-Pakete, JSON, JWT-Authentifizierung und Client-Code

Nachdem unsere ASP.NET Core Web API läuft, betrachten wir die Client-Seite: Wie kommunizieren eine Next.js/TypeScript-Webanwendung oder ein anderer C#-Microservice sicher, typsicher und fehlertolerant mit einer Web API?

In diesem Leitfaden analysieren wir den exakten Aufbau von HTTP-Request- und Response-Paketen, die kryptografische Struktur von JWT (JSON Web Token), die Diagnose typischer HTTP-Fehlercodes sowie produktionsreife Client-Implementierungen in TypeScript und C# (IHttpClientFactory).

Was Sie in dieser Lektion lernen:
1. Zeilenweise Analyse eines HTTP/2-Requests und einer HTTP-Response.
2. Diagnose-Tabelle für HTTP-Fehlercodes (400, 401, 403, 404, 415, 422, 429, 500).
3. Funktionsweise von JWT (Header.Payload.Signature) und Authorization: Bearer.
4. Zentraler Next.js / TypeScript API-Client (src/services/api-client.ts und products.service.ts).
5. Vermeidung von Socket Exhaustion in C# durch IHttpClientFactory und SocketsHttpHandler.
6. CORS (Cross-Origin Resource Sharing) in ASP.NET Core sauber konfigurieren.
API-Kommunikation mit HTTPS, JSON und JWT Bearer Token

1. Röntgenbild eines HTTP-Requests und einer HTTP-Response

POST /api/products HTTP/2                          <-- 1. REQUEST LINE: Methode + Pfad + Protokoll
Host: api.dgtalhat.com                             <-- 2. ZIEL-HOST
Content-Type: application/json; charset=utf-8      <-- 3. DATENFORMAT DES BODYS (Sonst HTTP 415!)
Accept: application/json                           <-- 4. ERWARTETES ANTWORTFORMAT
Accept-Language: de-DE                             <-- 5. SPRACHWAHL DES CLIENTS
Authorization: Bearer eyJhbGciOiJIUzI1NiIs...      <-- 6. JWT BEARER TOKEN (Sonst HTTP 401!)
                                                   <-- 7. LEERZEILE (Trennt Header und Body)
{                                                  <-- 8. JSON REQUEST BODY
  "name": "DHRevora Cloud POS Enterprise-Lizenz",
  "sku": "DH-REV-01",
  "unitPrice": 9500.00,
  "stockQuantity": 100
}

2. Diagnose-Tabelle der wichtigsten HTTP-Fehlercodes

Statuscode Bedeutung Ursache & Lösung
400 Bad Request Ungültiges JSON oder Pflichtfeld im Request-DTO fehlt.
401 Unauthorized Kein oder abgelaufenes JWT im Authorization: Bearer-Header.
403 Forbidden Gültiges JWT, aber fehlende Rolle/Berechtigung (z. B. kein Admin).
415 Unsupported Media Type Header Content-Type: application/json wurde beim POST/PUT vergessen.
422 Unprocessable Entity JSON formal korrekt, aber eine Domänenregel wurde verletzt.
429 Too Many Requests Rate-Limit erreicht; Retry-After-Header beachten.

3. Produktionsreifer TypeScript / Next.js API-Client

// 1. Dateipfad: 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 = "de", 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,
    signal: options.signal ?? AbortSignal.timeout(timeoutMs),
  });

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

  if (response.status === 204) {
    return null as TResponse;
  }

  return (await response.json()) as TResponse;
}
// 2. Dateipfad: 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" = "de") =>
    apiRequest<ProductDto[]>("/products", { method: "GET", locale }),

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

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

4. C# (.NET) Typed HttpClient mit IHttpClientFactory

// Dateipfad: 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;

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;

    public ErpAccountingClient(HttpClient httpClient)
    {
        _httpClient = httpClient;
    }

    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);

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

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

// Registrierung in Program.cs:
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");
})
.ConfigurePrimaryHttpMessageHandler(() => new SocketsHttpHandler
{
    PooledConnectionLifetime = TimeSpan.FromMinutes(5)
});

5. CORS-Konfiguration in Program.cs

builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowedFrontendOrigins", policy =>
    {
        policy.WithOrigins("https://dgtalhat.com", "http://localhost:3000")
              .AllowAnyHeader()
              .AllowAnyMethod()
              .AllowCredentials();
    });
});

var app = builder.Build();
app.UseCors("AllowedFrontendOrigins");
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();

War dieser Engineering-Leitfaden hilfreich für Sie?

Liken oder teilen Sie diesen Beitrag mit Ihrem Team und Netzwerk.

1 Aufrufe
Diesen Leitfaden teilen: