DEV Community

Vedika Intelligence
Vedika Intelligence

Posted on

Beyond JSON: Building Type-Safe API Integrations with TypeScript and Vedika [2026-02]

When we start building applications, we often treat API integration as a simple "fetch and print" task. We send a JSON object, get a JSON response, and move on. However, as applications grow, relying on loose typing (any) leads to runtime errors that are incredibly frustrating to debug.

In this article, we’re going to build a robust, type-safe integration for the Vedika Astrology API. While the domain (Vedic astrology) might seem niche, the technical requirements—specifically handling datetime objects, geospatial coordinates, and unstructured AI responses—make it a perfect playground for demonstrating TypeScript's power.

The Problem: The "Any" Trap

Consider a naive implementation:

const response = await fetch('/api/astrology', {
  method: 'POST',
  body: JSON.stringify({
    question: "When will I get a promotion?",
    birthDetails: {
      // What type is this? What happens if I miss a field?
    }
  })
});

const data = await response.json();
console.log(data.insights); // Runtime crash if 'insights' is missing
Enter fullscreen mode Exit fullscreen mode

This code is brittle. If you misspell insights as insights, TypeScript won't stop you, and you’ll get a runtime error. If the API changes its structure, your code breaks silently until a user encounters the issue.

The Solution: Strict Interfaces

To solve this, we must define exactly what the API expects and what it returns. We will use TypeScript interfaces to enforce this contract.

Step 1: Define the Data Structures

Vedika requires two main inputs: a question string and birthDetails (which includes a datetime, latitude, and longitude).

First, let's define the BirthDetails interface. This ensures we capture the location and time accurately.

interface BirthDetails {
  datetime: string; // ISO 8601 format is standard
  lat: number;
  lng: number;
}
Enter fullscreen mode Exit fullscreen mode

Next, let's define the request payload.

interface VedikaQueryInput {
  question: string;
  birthDetails: BirthDetails;
}
Enter fullscreen mode Exit fullscreen mode

Step 2: Define the Response Schema

The API returns an AI-generated response. We need to anticipate what that looks like. We'll define an interface for the root response, likely containing an array of insights or an analysis object.

interface VedikaResponse {
  success: boolean;
  data: {
    insights: string[]; // Array of string insights
    summary: string;
  } | null;
  error?: string;
}
Enter fullscreen mode Exit fullscreen mode

Step 3: The Type-Safe Client

Now, let's build the actual function. We will wrap the native fetch API in a typed function. This acts as our client, handling the networking and ensuring type safety at the boundary.


typescript
const API_BASE_URL = 'https
Enter fullscreen mode Exit fullscreen mode

Top comments (0)