API Endpoints

Creating and structuring API endpoints

API Endpoints

Route Handler Pattern

if (path === '/api/staff/news' && request.method === 'GET') {
  const userId = await verifyJWT(getAuthToken(request), env.JWT_SECRET)
  if (!userId) return unauthorized()
  
  if (!await hasPermission(userId, 'news:read', env)) {
    return forbidden()
  }
  
  const news = await env.DB.prepare('SELECT * FROM news').all()
  return json(news.results)
}

Response Helpers

  • json(data, status) - JSON response
  • unauthorized() - 401 response
  • forbidden() - 403 response
  • notFound() - 404 response
  • badRequest(message) - 400 response

Error Handling

try {
  const result = await performOperation()
  return json(result)
} catch (error) {
  return json({ error: 'Internal server error' }, 500)
}