Skip to Content
Next-TS-API 1.0 is released 🎉
DocsExamples

Examples

This page provides practical examples of using Next-TS-API in common scenarios.

Basic CRUD Operations

Todo List API

A complete example of a Todo List API with type-safe endpoints:

// app/api/todos/route.ts import { NextApiRequest } from 'next-ts-api'; import { NextResponse } from 'next/server'; interface Todo { id: string; title: string; completed: boolean; } const todos: Todo[] = []; // GET /api/todos export async function GET( request: NextApiRequest<null, { completed?: string; }> ) { const searchParams = request.nextUrl.searchParams; const completed = searchParams.get('completed'); return NextResponse.json( todos.filter(todo => todo.completed === (completed === 'true')) ); } // POST /api/todos export async function POST( request: NextApiRequest<{ title: string; }> ) { const { title } = await request.json(); const newTodo: Todo = { id: Math.random().toString(), title, completed: false }; return NextResponse.json(newTodo); } // PUT /api/todos export async function PUT( request: NextApiRequest<{ id: string; title?: string; completed?: boolean; }> ) { const updates = await request.json(); // Example response - in real app, update in database return NextResponse.json({ id: updates.id, title: updates.title, completed: updates.completed }); } // DELETE /api/todos/[id] export async function DELETE( request: NextApiRequest, { params }: { params: { id: string } } ) { const { id } = params; // Example response - in real app, delete from database return NextResponse.json({ success: true, deletedId: id }); }

Using the API Client

// lib/api.ts import { createNextFetchApi } from "next-ts-api"; import { type ApiRoutes } from "../types/next-ts-api"; export const api = createNextFetchApi<ApiRoutes>();
// app/todos/page.tsx 'use client'; import { api } from '@/lib/api'; import { useState, useEffect } from 'react'; interface Todo { id: string; title: string; completed: boolean; } export default function TodosPage() { const [todos, setTodos] = useState<Todo[]>([]); // Fetch completed todos const fetchTodos = async () => { const response = await api('todos', { method: 'GET', query: { completed: 'true' } }); const data = await response.json(); setTodos(data); }; // Create a new todo const createTodo = async (title: string) => { const response = await api('todos', { method: 'POST', body: { title } }); const newTodo = await response.json(); setTodos([...todos, newTodo]); }; // Update a todo const updateTodo = async (todo: Todo) => { const response = await api('todos', { method: 'PUT', body: todo }); const updatedTodo = await response.json(); setTodos(todos.map(t => t.id === updatedTodo.id ? updatedTodo : t)); }; // Delete a todo const deleteTodo = async (id: string) => { await api(`todos/[id]`, { method: 'DELETE', params: { id } }); setTodos(todos.filter(t => t.id !== id)); }; return ( <div> {/* Your JSX implementation here */} </div> ); }

Next Steps

Last updated on