Add a Typed TypeScript Client for a FastAPI AI Endpoint

Add a Typed TypeScript Client for a FastAPI AI Endpoint

Published on

0

views

This article demonstrates how to build a robust, typed TypeScript client for a FastAPI AI summarization endpoint. It covers essential practices including request-response interface mirroring, client-side input validation, custom error classes with HTTP status handling, and runtime response shape checks, providing compile-time safety and clean contract boundaries for your frontend.

You now have a working FastAPI summarization endpoint. The next practical step is giving the frontend (or any TypeScript service) a clean, typed way to call it.

A typed client is not glamorous. It is the difference between “the response might be anything” and “TypeScript tells me exactly what shape I will get, and the compiler complains when I misuse it.” That small amount of discipline pays for itself the first time someone changes a field name.

The Short Answer

Generate or hand-write a thin TypeScript client that matches the FastAPI request and response models, uses a single fetch wrapper with proper error handling, and exposes a simple async function. Keep the client focused on one endpoint for the first version. Add retries, interceptors, or a full SDK only when the extra complexity is justified by real usage.

Low-angle shot of a frontend engineer reviewing TypeScript client interfaces and FastAPI response models on a laptop.

What Product Problem This Solves

The frontend needs to ask for a summary without knowing (or caring) about OpenAI keys, token counts, or finish reasons. At the same time, the TypeScript code should not treat the response as an untyped any. A small, typed client gives both sides what they need: the backend stays the single source of truth for validation and logging, and the frontend gets compile-time safety and clear error paths.

Minimal Working Implementation

Assume the FastAPI endpoint from the previous article is running at http://localhost:8000/v1/summarize. Here is a complete, dependency-light TypeScript client.

TypeScript

// src/api/summarizeClient.ts

export type SummarizeStyle = "concise" | "bullet" | "technical";

export interface SummarizeRequest {
  text: string;
  style?: SummarizeStyle;
  max_tokens?: number;
}

export interface Usage {
  prompt_tokens: number;
  completion_tokens: number;
  total_tokens: number;
}

export interface SummarizeResponse {
  summary: string;
  style: string;
  finish_reason: string;
  model: string;
  usage: Usage;
  request_id?: string | null;
}

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

const DEFAULT_BASE_URL = process.env.NEXT_PUBLIC_API_BASE_URL ?? "http://localhost:8000";

export async function summarizeText(
  request: SummarizeRequest,
  options?: { baseUrl?: string; signal?: AbortSignal }
): Promise<SummarizeResponse> {
  const baseUrl = options?.baseUrl ?? DEFAULT_BASE_URL;
  const url = `${baseUrl}/v1/summarize`;

  // Basic client-side guard – the server still does the real validation
  if (!request.text || request.text.trim().length < 20) {
    throw new SummarizeApiError("Text must be at least 20 characters", 400);
  }

  const response = await fetch(url, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Accept: "application/json",
    },
    body: JSON.stringify({
      text: request.text,
      style: request.style ?? "concise",
      max_tokens: request.max_tokens ?? 180,
    }),
    signal: options?.signal,
  });

  let body: unknown;
  try {
    body = await response.json();
  } catch {
    throw new SummarizeApiError(
      `Invalid JSON response (status ${response.status})`,
      response.status
    );
  }

  if (!response.ok) {
    const detail =
      typeof body === "object" && body !== null && "detail" in body
        ? String((body as any).detail)
        : `Request failed with status ${response.status}`;
    throw new SummarizeApiError(detail, response.status, body);
  }

  // Runtime shape check – TypeScript types are not runtime guarantees
  const data = body as SummarizeResponse;
  if (typeof data.summary !== "string" || !data.usage) {
    throw new SummarizeApiError("Unexpected response shape from server", 502, body);
  }

  return data;
}

Usage from a React component or any TypeScript module is then straightforward:

TypeScript

import { summarizeText, SummarizeApiError } from "@/api/summarizeClient";

async function handleSummarize(rawText: string) {
  try {
    const result = await summarizeText({
      text: rawText,
      style: "technical",
    });
    console.log(result.summary);
    console.log("Tokens used:", result.usage.total_tokens);
  } catch (err) {
    if (err instanceof SummarizeApiError) {
      console.error(`API error ${err.status}: ${err.message}`);
    } else {
      console.error("Unexpected error", err);
    }
  }
}

This is the smallest version that still gives the frontend a reliable contract.

Why the Types Matter

The request and response interfaces mirror the Pydantic models on the backend. When the backend later renames a field or changes a type, the TypeScript compiler becomes an early warning system instead of a silent runtime surprise.

I once watched a frontend silently ignore a renamed finish_reason field for two days because everything was typed as any. The bug only appeared when someone tried to log the value. Typed clients turn that class of mistake into a compile error.

Client-Side Validation Is Still Useful

The server performs the real validation. The client still does a quick length check so the user gets immediate feedback and we avoid an unnecessary network round-trip for obviously invalid input. That is not duplication; it is layered defense.

The same principle applies to the runtime shape check after response.json(). TypeScript types disappear at runtime. A few lines that confirm summary is a string and usage exists protect you from a mismatched deployment or a proxy that rewrote the body.

Error Handling That Stays Honest

SummarizeApiError carries the HTTP status and the original body. Callers can distinguish a 400 (bad input) from a 504 (timeout) from a 502 (upstream model problem) without parsing strings. The frontend can then show the appropriate message or retry strategy.

The model can suggest the summary; the application still has to decide whether the call succeeded and what to show the user. A typed error class makes that decision explicit.

Wide-angle shot of an engineer debugging custom API error handling and status code logic in an IDE.

What About Streaming or More Endpoints?

This client is deliberately synchronous and single-purpose. Streaming responses and additional endpoints belong in later iterations once the basic path is proven useful and the latency numbers are known.

Before adding an agent, see whether a deterministic workflow is enough. Before adding a full OpenAPI-generated SDK, see whether the hand-written client already meets the need. The extra complexity has to earn its place.

What Was Tested and What Remains Uncertain

I tested the client against the FastAPI endpoint with valid short and medium inputs, deliberately short text (to hit the client guard), and forced server errors (timeout and empty content). The typed response and the custom error class behaved as expected.

I have not tested AbortController cancellation under slow networks, nor have I measured the effect of concurrent calls from a React Strict Mode double-mount. Those checks belong in later articles once the feature sees real frontend traffic. Exact base-URL configuration and CORS settings must be verified for each deployment environment.

Practical Conclusion

A typed TypeScript client for a FastAPI AI endpoint is ordinary frontend engineering with one important extra rule: never treat the model response as an untyped blob. Mirror the backend contract, perform a light runtime check, and surface clear errors.

Start with the smallest version that can answer the product question. In this case the question is “Can the frontend call the summarization feature safely and with compile-time confidence?” The code above is that version.

Build real applications. Verify every step.

Last updated:

Share:

Leave a comment

Related Articles

What to Verify Before Building with GPT-6.1 Sol
Build an AI Feature |

What to Verify Before Building with GPT-6.1 Sol

Before building production-facing applications with GPT-6.1 Sol, running a disciplined verification checklist is essential. This guide outlines critical pre-flight checks—confirming model availability, measuring context windows, testing structured outputs and tool calling, monitoring latency and costs, and evaluating error modes. Verifying these core capabilities beforehand prevents unexpected failures and ensures robust application performance under real-world usage conditions.

0
Build a Small GPT-6.1 Sol Summarization Endpoint
Build an AI Feature |

Build a Small GPT-6.1 Sol Summarization Endpoint

This article demonstrates how to build a production-ready summarization endpoint using FastAPI and the GPT-6.1 Sol model. It covers essential backend practices including input length validation, style constraints, hard timeouts, finish reason verification, and structured operational logging, providing a reliable foundation for adding safe AI features to your application architecture.

0
Show Task Progress in a Next.js AI Application
Build an AI Feature |

Show Task Progress in a Next.js AI Application

This article demonstrates how to build a practical progress tracker for AI features in Next.js without complex queues or WebSockets. Using a lightweight React component, it covers multi-stage loading states, elapsed time counters, abort-controller cancellation, and clear error handling, ensuring users stay informed during slow model inference calls.

0