If you’ve been writing TypeScript for any amount of time, you know the pain of the any keyword. It’s the siren song of convenience—easy to type, but a disaster waiting to happen at runtime. One day, your API returns a string when you expect an object, or a field you thought was required is suddenly missing.
When integrating with external APIs, especially AI-driven ones, this uncertainty is amplified. The response structure might be complex, nested, or evolve without notice. This is where TypeScript shines. It allows us to define a contract before the data hits the wire, ensuring our application is robust, maintainable, and predictable.
In this article, we’ll integrate the Vedika Astrology API into a TypeScript application. We will focus on the "how" and the "why," demonstrating how to build a type-safe client that queries for astrological insights based on birth details.
The Setup
Before we write any code, we need a target. The Vedika API is an AI-powered Vedic astrology service. It requires a single endpoint, POST /api/v1/astrology/query, which takes a question and birth details to generate a reading.
For this example, we’ll assume you have a Node.js environment set up. Create a new folder, initialize a project, and install fetch (built-in in Node 18+) or axios. For strict typing, we’ll stick to the native fetch API to keep dependencies low.
mkdir vedika-ts-client
cd vedika-ts-client
npm init -y
Step 1: Define Your Types
The first rule of TypeScript integration is: Define the Shape.
We need to map the JSON structure of the Vedika API request and response to TypeScript interfaces. This happens in two parts: defining the Request payload and defining the Response payload.
1.1 The Request Interface
The API requires a question (string) and a birthDetails object. The birthDetails object needs a datetime (ISO 8601 string), latitude, and longitude.
// types.ts
export interface BirthDetails {
datetime: string; // ISO 8601 format, e.g., "2000-01-01T12:00:00Z"
lat: number;
lng: number;
}
export interface AstrologyQueryRequest {
question: string;
birthDetails: BirthDetails;
}
1.2 The Response Interface
The API returns a JSON object. While the exact field names might vary slightly depending on the specific AI model version, we anticipate a structure containing an insight field and metadata.
export interface AstrologyResponse {
insight: string;
// Future-proofing: Adding other potential fields as comments
// timestamp?: number;
// confidence?: number;
}
By defining these interfaces, we gain immediate feedback. If you misspell datetime as date, TypeScript will scream at you immediately in your IDE.
Step 2: Implementing the Client
Now that our types are defined, we can build the client. We will create a function that accepts the AstrologyQueryRequest, sends
Top comments (0)