Examples
Examples
Here are practical examples showing how to use our API and integrate with your applications.
Basic Usage
Fetching User Data
async function getUser(userId: string) {
try {
const response = await fetch(`/api/users/${userId}`, {
headers: {
'Authorization': `Bearer ${process.env.API_KEY}`,
},
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const user = await response.json();
return user;
} catch (error) {
console.error('Error fetching user:', error);
throw error;
}
}
Creating a New User
async function createUser(userData: { name: string; email: string }) {
try {
const response = await fetch('/api/users', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(userData),
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const newUser = await response.json();
return newUser;
} catch (error) {
console.error('Error creating user:', error);
throw error;
}
}
React Integration
User List Component
import { useState, useEffect } from 'react';
interface User {
id: string;
name: string;
email: string;
created_at: string;
}
export function UserList() {
const [users, setUsers] = useState<User[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
async function fetchUsers() {
try {
const response = await fetch('/api/users');
if (!response.ok) {
throw new Error('Failed to fetch users');
}
const data = await response.json();
setUsers(data.users);
} catch (err) {
setError(err instanceof Error ? err.message : 'An error occurred');
} finally {
setLoading(false);
}
}
fetchUsers();
}, []);
if (loading) return <div>Loading...</div>;
if (error) return <div>Error: {error}</div>;
return (
<div>
<h2>Users</h2>
<ul>
{users.map((user) => (
<li key={user.id}>
{user.name} ({user.email})
</li>
))}
</ul>
</div>
);
}
Create User Form
import { useState } from 'react';
export function CreateUserForm() {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [submitting, setSubmitting] = useState(false);
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
setSubmitting(true);
try {
const response = await fetch('/api/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ name, email }),
});
if (response.ok) {
setName('');
setEmail('');
alert('User created successfully!');
} else {
alert('Failed to create user');
}
} catch (error) {
alert('Error creating user');
} finally {
setSubmitting(false);
}
}
return (
<form onSubmit={handleSubmit}>
<div>
<label htmlFor="name">Name:</label>
<input
id="name"
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
required
/>
</div>
<div>
<label htmlFor="email">Email:</label>
<input
id="email"
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
/>
</div>
<button type="submit" disabled={submitting}>
{submitting ? 'Creating...' : 'Create User'}
</button>
</form>
);
}
Next.js API Routes
User API Route
// app/api/users/route.ts
import { NextRequest, NextResponse } from 'next/server';
export async function GET(request: NextRequest) {
const { searchParams } = new URL(request.url);
const limit = parseInt(searchParams.get('limit') || '10');
const offset = parseInt(searchParams.get('offset') || '0');
// Your database logic here
const users = await getUsers({ limit, offset });
return NextResponse.json({
users,
total: users.length,
limit,
offset,
});
}
export async function POST(request: NextRequest) {
try {
const { name, email } = await request.json();
// Validation
if (!name || !email) {
return NextResponse.json(
{ error: { code: 'MISSING_FIELDS', message: 'Name and email are required' } },
{ status: 400 }
);
}
// Your database logic here
const newUser = await createUser({ name, email });
return NextResponse.json(newUser, { status: 201 });
} catch (error) {
return NextResponse.json(
{ error: { code: 'INTERNAL_ERROR', message: 'Failed to create user' } },
{ status: 500 }
);
}
}
Error Handling
Comprehensive Error Handler
class APIError extends Error {
constructor(
public status: number,
public code: string,
message: string,
public details?: any
) {
super(message);
this.name = 'APIError';
}
}
async function apiRequest<T>(
endpoint: string,
options: RequestInit = {}
): Promise<T> {
const response = await fetch(endpoint, {
headers: {
'Content-Type': 'application/json',
...options.headers,
},
...options,
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
throw new APIError(
response.status,
errorData.error?.code || 'UNKNOWN_ERROR',
errorData.error?.message || 'An unknown error occurred',
errorData.error?.details
);
}
return response.json();
}