Master Ky HTTP client patterns for Google Antigravity IDE elegant API requests
# Ky HTTP Client Patterns for Google Antigravity IDE
Build elegant HTTP requests with Ky using Google Antigravity IDE. This guide covers configuration, interceptors, retry logic, and type-safe API clients.
## Client Configuration
```typescript
// src/lib/api.ts
import ky from "ky";
export const api = ky.create({
prefixUrl: process.env.NEXT_PUBLIC_API_URL,
timeout: 30000,
retry: {
limit: 3,
methods: ["get", "put", "delete"],
statusCodes: [408, 413, 429, 500, 502, 503, 504],
backoffLimit: 3000,
},
hooks: {
beforeRequest: [
(request) => {
const token = getAuthToken();
if (token) {
request.headers.set("Authorization", "Bearer " + token);
}
},
],
beforeRetry: [
async ({ request, options, error, retryCount }) => {
console.log("Retrying request:", retryCount, error.message);
},
],
afterResponse: [
async (request, options, response) => {
if (response.status === 401) {
const refreshed = await refreshToken();
if (refreshed) {
request.headers.set("Authorization", "Bearer " + refreshed);
return ky(request, options);
}
window.location.href = "/login";
}
return response;
},
],
beforeError: [
async (error) => {
const { response } = error;
if (response) {
const body = await response.json().catch(() => ({}));
error.message = body.message || error.message;
}
return error;
},
],
},
});
```
## Type-Safe API Client
```typescript
// src/api/users.ts
import { api } from "@/lib/api";
import type { User, CreateUser, UpdateUser } from "@/types";
export const usersApi = {
list: async (params?: { page?: number; limit?: number; search?: string }) => {
const searchParams = new URLSearchParams();
if (params?.page) searchParams.set("page", String(params.page));
if (params?.limit) searchParams.set("limit", String(params.limit));
if (params?.search) searchParams.set("q", params.search);
return api.get("users", { searchParams }).json<{ users: User[]; total: number }>();
},
get: async (id: string) => {
return api.get("users/" + id).json<User>();
},
create: async (data: CreateUser) => {
return api.post("users", { json: data }).json<User>();
},
update: async (id: string, data: UpdateUser) => {
return api.patch("users/" + id, { json: data }).json<User>();
},
delete: async (id: string) => {
await api.delete("users/" + id);
},
uploadAvatar: async (id: string, file: File) => {
const formData = new FormData();
formData.append("avatar", file);
return api.post("users/" + id + "/avatar", { body: formData }).json<{ avatarUrl: string }>();
},
};
```
## React Query Integration
```typescript
// src/hooks/useUsers.ts
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { usersApi } from "@/api/users";
export function useUsers(params?: { page?: number; search?: string }) {
return useQuery({
queryKey: ["users", params],
queryFn: () => usersApi.list(params),
});
}
export function useUser(id: string) {
return useQuery({
queryKey: ["users", id],
queryFn: () => usersApi.get(id),
enabled: !!id,
});
}
export function useCreateUser() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: usersApi.create,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["users"] });
},
});
}
export function useUpdateUser() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({ id, data }: { id: string; data: UpdateUser }) => usersApi.update(id, data),
onSuccess: (user) => {
queryClient.setQueryData(["users", user.id], user);
queryClient.invalidateQueries({ queryKey: ["users"] });
},
});
}
```
## Best Practices for Google Antigravity IDE
When using Ky with Google Antigravity, configure retry logic for resilience. Use hooks for auth token refresh. Create type-safe API clients. Integrate with React Query for caching. Let Gemini 3 generate API clients from OpenAPI specs.
Google Antigravity excels at building robust HTTP clients with Ky.This Ky prompt is ideal for developers working on:
By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their ky implementations.
Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.
This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.
You can modify the prompt by adding specific requirements, constraints, or preferences. For Ky projects, consider mentioning your framework version, coding style, and any specific libraries you're using.