API Routes
Phyre supports two ways to define API routes: File-based and Config-based.
File-based API Routes
Create a file and export HTTP method functions:
plaintext
src/server/api/ └── user/ └── profile/ └── settings.js
javascript
// src/server/api/user/profile/settings.js export function GET(req, res) { res.json({ data: 'settings' }); } export function POST(req, res) { const body = req.body; res.json({ data: 'settings updated', body }); }
Result:
• GET /api/user/profile/settings
• POST /api/user/profile/settings
Supported methods: GET, POST, PUT, PATCH, DELETE
Config-based API Routes
Define multiple routes in a single file using a config object:
javascript
// src/server/api/user.js export const config = { routes: [ { path: '/profile/settings', method: 'GET', handler: getSettings }, { path: '/profile/settings', method: 'POST', handler: updateSettings } ] }; function getSettings(req, res) { res.json({ data: 'settings' }); } function updateSettings(req, res) { res.json({ data: 'settings updated' }); }
Result:
• GET /api/user/profile/settings
• POST /api/user/profile/settings
💡 Tip: Use regular functions (not arrow functions) to avoid hoisting errors when declared after usage.
Dynamic Parameters
Use [param] in file names for dynamic routes:
plaintext
src/server/api/ └── posts/ └── [id].js
javascript
// src/server/api/posts/[id].js export function GET(req, res) { const { id } = req.params; res.json({ postId: id }); }
GET /api/posts/123 → req.params.id = "123"
Request Body
Access request body in POST/PUT/PATCH handlers:
javascript
export function POST(req, res) { const { title, content } = req.body; // Save to database... res.json({ success: true, post: { title, content } }); }
Query Parameters
Access query parameters:
javascript
// GET /api/search?q=phyre&limit=10 export function GET(req, res) { const { q, limit } = req.query; res.json({ query: q, limit: limit || 10 }); }
Response Helpers
Express response methods are available:
javascript
export function GET(req, res) { // JSON response res.json({ data: 'value' }); // Status code res.status(201).json({ created: true }); // Error res.status(404).json({ error: 'Not found' }); // Redirect res.redirect('/other-route'); // Send file res.sendFile('/path/to/file'); }
When to use which?
| Scenario | Use |
|---|---|
| Simple CRUD on one resource | File-based |
| Multiple related endpoints | Config-based |
| Need middleware per-route | Both support it |
