Skip to content

Instantly share code, notes, and snippets.

@suciuvlad
Created November 9, 2023 20:28
Show Gist options
  • Save suciuvlad/0b1d86cd8fbfa937674fe63f30c08044 to your computer and use it in GitHub Desktop.
Save suciuvlad/0b1d86cd8fbfa937674fe63f30c08044 to your computer and use it in GitHub Desktop.
Open API Typescript Client - Simplified Example
// ApiConfiguration.ts
export class ApiConfiguration {
public static readonly BASE_URL: string = 'https://api.example.com';
// possibly include API keys, custom headers, etc.
}
// HttpClient.ts
import axios, { AxiosInstance } from 'axios';
export class HttpClient {
private axiosInstance: AxiosInstance;
constructor(baseURL: string) {
this.axiosInstance = axios.create({
baseURL
});
}
public async get<T>(url: string): Promise<T> {
const response = await this.axiosInstance.get<T>(url);
return response.data;
}
public async post<T>(url: string, data: any): Promise<T> {
const response = await this.axiosInstance.post<T>(url, data);
return response.data;
}
// Add methods for PUT, DELETE, etc.
}
import { PetApi } from './PetApi';
import { HttpClient } from './HttpClient';
import { ApiConfiguration } from './ApiConfiguration';
const httpClient = new HttpClient(ApiConfiguration.BASE_URL);
const petApi = new PetApi(httpClient);
const main = async () => {
try {
const newPet = await petApi.addPet({ id: 0, name: 'Fido' });
console.log(newPet);
const pet = await petApi.getPetById(newPet.id);
console.log(pet);
} catch (error) {
console.error('Error calling API', error);
}
};
main();
// Pet.ts
export interface Pet {
id: number;
name: string;
tag?: string;
}
// PetApi.ts
import { Pet } from './Pet';
import { HttpClient } from './HttpClient'; // This is a simplified example of an HTTP client
export class PetApi {
constructor(private httpClient: HttpClient) {}
public async getPetById(petId: number): Promise<Pet> {
return this.httpClient.get<Pet>(`/pets/${petId}`);
}
public async addPet(pet: Pet): Promise<Pet> {
return this.httpClient.post<Pet>('/pets', pet);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment