also looking at this
Deploy: uniform auth session model (main → production)
#7
282 files
+3028
-64856
| @@ -1,818 +0,0 @@ | ||
| 1 | # Build an API | |
| 2 | ||
| 3 | This tutorial will guide you through building a RESTful API with Stacks. You will learn how to create routes, actions, controllers, handle validation, implement authentication, and interact with the database. | |
| 4 | ||
| 5 | ## API Architecture Overview | |
| 6 | ||
| 7 | Stacks follows a clean, Laravel-inspired architecture for APIs: | |
| 8 | ||
| 9 | - **Routes** - Define API endpoints and map them to handlers | |
| 10 | - **Actions** - Reusable business logic units | |
| 11 | - **Controllers** - Group related request handlers | |
| 12 | - **Middleware** - Handle cross-cutting concerns (auth, logging, etc.) | |
| 13 | - **Models** - Database interactions | |
| 14 | ||
| 15 | ## Creating Routes | |
| 16 | ||
| 17 | Routes are defined in the `routes/` directory. The main API routes go in `routes/api.ts`. | |
| 18 | ||
| 19 | ### Basic Routes | |
| 20 | ||
| 21 | ```typescript | |
| 22 | // routes/api.ts | |
| 23 | import { response, route } from '@stacksjs/router' | |
| 24 | ||
| 25 | // Simple GET route with inline handler | |
| 26 | route.get('/', () => response.text('Hello, World!')) | |
| 27 | ||
| 28 | // Return JSON | |
| 29 | route.get('/status', () => response.json({ | |
| 30 | status: 'ok', | |
| 31 | timestamp: Date.now(), | |
| 32 | })) | |
| 33 | ||
| 34 | // Route with path parameters | |
| 35 | route.get('/users/{id}', (request) => { | |
| 36 | const userId = request.param('id') | |
| 37 | return response.json({ userId }) | |
| 38 | }) | |
| 39 | ||
| 40 | // Different HTTP methods | |
| 41 | route.post('/users', 'Actions/User/CreateUserAction') | |
| 42 | route.put('/users/{id}', 'Actions/User/UpdateUserAction') | |
| 43 | route.patch('/users/{id}', 'Actions/User/PatchUserAction') | |
| 44 | route.delete('/users/{id}', 'Actions/User/DeleteUserAction') | |
| 45 | ``` | |
| 46 | ||
| 47 | ### Route Groups | |
| 48 | ||
| 49 | Group routes with shared configuration: | |
| 50 | ||
| 51 | ```typescript | |
| 52 | // routes/api.ts | |
| 53 | import { route } from '@stacksjs/router' | |
| 54 | ||
| 55 | // Group with prefix | |
| 56 | route.group({ prefix: '/api/v1' }, () => { | |
| 57 | route.get('/users', 'Actions/User/ListUsersAction') | |
| 58 | route.get('/users/{id}', 'Actions/User/GetUserAction') | |
| 59 | route.post('/users', 'Actions/User/CreateUserAction') | |
| 60 | }) | |
| 61 | ||
| 62 | // Group with middleware | |
| 63 | route.group({ middleware: 'auth' }, () => { | |
| 64 | route.get('/me', 'Actions/Auth/AuthUserAction') | |
| 65 | route.post('/logout', 'Actions/Auth/LogoutAction') | |
| 66 | }) | |
| 67 | ||
| 68 | // Combine prefix and middleware | |
| 69 | route.group({ prefix: '/admin', middleware: ['auth', 'admin'] }, () => { | |
| 70 | route.get('/dashboard', 'Actions/Admin/DashboardAction') | |
| 71 | route.get('/users', 'Actions/Admin/ListUsersAction') | |
| 72 | }) | |
| 73 | ``` | |
| 74 | ||
| 75 | ### Special Routes | |
| 76 | ||
| 77 | Stacks provides convenience methods for common routes: | |
| 78 | ||
| 79 | ```typescript | |
| 80 | // Health check endpoint (GET /health) | |
| 81 | route.health() | |
| 82 | ||
| 83 | // Route to an action | |
| 84 | route.action('/example') // equivalent to route.get('/example', 'ExampleAction') | |
| 85 | ||
| 86 | // Route to a job | |
| 87 | route.job('/process') // equivalent to route.get('/process', 'ProcessJob') | |
| 88 | ``` | |
| 89 | ||
| 90 | ## Creating Actions | |
| 91 | ||
| 92 | Actions are reusable units of business logic. They can be called from routes, CLI commands, event listeners, or other actions. | |
| 93 | ||
| 94 | ### Generate an Action | |
| 95 | ||
| 96 | ```bash | |
| 97 | buddy make:action CreateUser | |
| 98 | ``` | |
| 99 | ||
| 100 | ### Action Structure | |
| 101 | ||
| 102 | ```typescript | |
| 103 | // app/Actions/User/CreateUserAction.ts | |
| 104 | import type { RequestInstance } from '@stacksjs/types' | |
| 105 | import { Action } from '@stacksjs/actions' | |
| 106 | import { response } from '@stacksjs/router' | |
| 107 | import { schema } from '@stacksjs/validation' | |
| 108 | ||
| 109 | export default new Action({ | |
| 110 | name: 'CreateUserAction', | |
| 111 | description: 'Create a new user', | |
| 112 | method: 'POST', | |
| 113 | ||
| 114 | // Define validation rules | |
| 115 | validations: { | |
| 116 | email: { | |
| 117 | rule: schema.string().email(), | |
| 118 | message: 'Email must be a valid email address.', | |
| 119 | }, | |
| 120 | password: { | |
| 121 | rule: schema.string().min(8).max(255), | |
| 122 | message: 'Password must be between 8 and 255 characters.', | |
| 123 | }, | |
| 124 | name: { | |
| 125 | rule: schema.string().min(2).max(100), | |
| 126 | message: 'Name must be between 2 and 100 characters.', | |
| 127 | }, | |
| 128 | }, | |
| 129 | ||
| 130 | // Handle the request | |
| 131 | async handle(request: RequestInstance) { | |
| 132 | const email = request.get('email') | |
| 133 | const password = request.get('password') | |
| 134 | const name = request.get('name') | |
| 135 | ||
| 136 | // Create the user (database operation) | |
| 137 | const user = await User.create({ | |
| 138 | email, | |
| 139 | password: await hash(password), | |
| 140 | name, | |
| 141 | }) | |
| 142 | ||
| 143 | return response.json({ | |
| 144 | message: 'User created successfully', | |
| 145 | user: { | |
| 146 | id: user.id, | |
| 147 | email: user.email, | |
| 148 | name: user.name, | |
| 149 | }, | |
| 150 | }, 201) | |
| 151 | }, | |
| 152 | }) | |
| 153 | ``` | |
| 154 | ||
| 155 | ### Action with Manual Validation | |
| 156 | ||
| 157 | You can also validate manually within the handle method: | |
| 158 | ||
| 159 | ```typescript | |
| 160 | // app/Actions/Auth/RegisterAction.ts | |
| 161 | import type { RequestInstance } from '@stacksjs/types' | |
| 162 | import { Action } from '@stacksjs/actions' | |
| 163 | import { Auth, register } from '@stacksjs/auth' | |
| 164 | import { response } from '@stacksjs/router' | |
| 165 | import { schema } from '@stacksjs/validation' | |
| 166 | ||
| 167 | export default new Action({ | |
| 168 | name: 'RegisterAction', | |
| 169 | description: 'Register a new user', | |
| 170 | method: 'POST', | |
| 171 | ||
| 172 | async handle(request: RequestInstance) { | |
| 173 | // Validate manually with custom messages | |
| 174 | await request.validate({ | |
| 175 | email: { | |
| 176 | rule: schema.string().email(), | |
| 177 | message: { | |
| 178 | email: 'Email must be a valid email address', | |
| 179 | }, | |
| 180 | }, | |
| 181 | password: { | |
| 182 | rule: schema.string().min(6).max(255), | |
| 183 | message: { | |
| 184 | min: 'Password must have a minimum of 6 characters', | |
| 185 | max: 'Password must have a maximum of 255 characters', | |
| 186 | }, | |
| 187 | }, | |
| 188 | name: { | |
| 189 | rule: schema.string().min(2).max(255), | |
| 190 | message: { | |
| 191 | min: 'Name must have a minimum of 2 characters', | |
| 192 | max: 'Name must have a maximum of 255 characters', | |
| 193 | }, | |
| 194 | }, | |
| 195 | }) | |
| 196 | ||
| 197 | const email = request.get('email') | |
| 198 | const password = request.get('password') | |
| 199 | const name = request.get('name') | |
| 200 | ||
| 201 | const result = await register({ email, password, name }) | |
| 202 | ||
| 203 | if (result) { | |
| 204 | const user = await Auth.getUserFromToken(result.token) | |
| 205 | ||
| 206 | return response.json({ | |
| 207 | token: result.token, | |
| 208 | user: { | |
| 209 | id: user?.id, | |
| 210 | email: user?.email, | |
| 211 | name: user?.name, | |
| 212 | }, | |
| 213 | }) | |
| 214 | } | |
| 215 | ||
| 216 | return response.error('Registration failed') | |
| 217 | }, | |
| 218 | }) | |
| 219 | ``` | |
| 220 | ||
| 221 | ## Creating Controllers | |
| 222 | ||
| 223 | Controllers group related request handlers. Use them when you have multiple related endpoints. | |
| 224 | ||
| 225 | ### Generate a Controller | |
| 226 | ||
| 227 | ```bash | |
| 228 | buddy make:controller User | |
| 229 | ``` | |
| 230 | ||
| 231 | ### Controller Structure | |
| 232 | ||
| 233 | ```typescript | |
| 234 | // app/Controllers/UserController.ts | |
| 235 | import type { RequestInstance } from '@stacksjs/types' | |
| 236 | import { Controller } from '@stacksjs/router' | |
| 237 | import { response } from '@stacksjs/router' | |
| 238 | ||
| 239 | export default class UserController extends Controller { | |
| 240 | // GET /users | |
| 241 | async index(request: RequestInstance) { | |
| 242 | const page = request.query('page', 1) | |
| 243 | const limit = request.query('limit', 10) | |
| 244 | ||
| 245 | const users = await User.paginate(page, limit) | |
| 246 | ||
| 247 | return response.json(users) | |
| 248 | } | |
| 249 | ||
| 250 | // GET /users/:id | |
| 251 | async show(request: RequestInstance) { | |
| 252 | const id = request.param('id') | |
| 253 | const user = await User.find(id) | |
| 254 | ||
| 255 | if (!user) { | |
| 256 | return response.notFound('User not found') | |
| 257 | } | |
| 258 | ||
| 259 | return response.json(user) | |
| 260 | } | |
| 261 | ||
| 262 | // POST /users | |
| 263 | async store(request: RequestInstance) { | |
| 264 | const data = request.only(['email', 'name', 'password']) | |
| 265 | ||
| 266 | const user = await User.create(data) | |
| 267 | ||
| 268 | return response.json(user, 201) | |
| 269 | } | |
| 270 | ||
| 271 | // PUT /users/:id | |
| 272 | async update(request: RequestInstance) { | |
| 273 | const id = request.param('id') | |
| 274 | const data = request.only(['email', 'name']) | |
| 275 | ||
| 276 | const user = await User.find(id) | |
| 277 | ||
| 278 | if (!user) { | |
| 279 | return response.notFound('User not found') | |
| 280 | } | |
| 281 | ||
| 282 | await user.update(data) | |
| 283 | ||
| 284 | return response.json(user) | |
| 285 | } | |
| 286 | ||
| 287 | // DELETE /users/:id | |
| 288 | async destroy(request: RequestInstance) { | |
| 289 | const id = request.param('id') | |
| 290 | const user = await User.find(id) | |
| 291 | ||
| 292 | if (!user) { | |
| 293 | return response.notFound('User not found') | |
| 294 | } | |
| 295 | ||
| 296 | await user.delete() | |
| 297 | ||
| 298 | return response.json({ message: 'User deleted' }) | |
| 299 | } | |
| 300 | } | |
| 301 | ``` | |
| 302 | ||
| 303 | Using the controller in routes: | |
| 304 | ||
| 305 | ```typescript | |
| 306 | // routes/api.ts | |
| 307 | import { route } from '@stacksjs/router' | |
| 308 | ||
| 309 | route.get('/users', 'Controllers/UserController@index') | |
| 310 | route.get('/users/{id}', 'Controllers/UserController@show') | |
| 311 | route.post('/users', 'Controllers/UserController@store') | |
| 312 | route.put('/users/{id}', 'Controllers/UserController@update') | |
| 313 | route.delete('/users/{id}', 'Controllers/UserController@destroy') | |
| 314 | ``` | |
| 315 | ||
| 316 | ## Validation | |
| 317 | ||
| 318 | Stacks provides a powerful validation system using schemas. | |
| 319 | ||
| 320 | ### Available Validation Rules | |
| 321 | ||
| 322 | ```typescript | |
| 323 | import { schema } from '@stacksjs/validation' | |
| 324 | ||
| 325 | // String validations | |
| 326 | schema.string() // Must be a string | |
| 327 | schema.string().email() // Must be valid email | |
| 328 | schema.string().url() // Must be valid URL | |
| 329 | schema.string().min(5) // Minimum length | |
| 330 | schema.string().max(100) // Maximum length | |
| 331 | schema.string().regex(/pattern/) // Must match pattern | |
| 332 | ||
| 333 | // Number validations | |
| 334 | schema.number() // Must be a number | |
| 335 | schema.number().min(0) // Minimum value | |
| 336 | schema.number().max(100) // Maximum value | |
| 337 | schema.number().positive() // Must be positive | |
| 338 | schema.number().integer() // Must be integer | |
| 339 | ||
| 340 | // Boolean | |
| 341 | schema.boolean() // Must be boolean | |
| 342 | ||
| 343 | // Array | |
| 344 | schema.array() // Must be array | |
| 345 | schema.array().min(1) // Minimum items | |
| 346 | schema.array().max(10) // Maximum items | |
| 347 | ||
| 348 | // Object | |
| 349 | schema.object() // Must be object | |
| 350 | ||
| 351 | // Optional fields | |
| 352 | schema.string().optional() // Field is optional | |
| 353 | ||
| 354 | // Nullable fields | |
| 355 | schema.string().nullable() // Can be null | |
| 356 | ``` | |
| 357 | ||
| 358 | ### Validation in Actions | |
| 359 | ||
| 360 | ```typescript | |
| 361 | export default new Action({ | |
| 362 | name: 'CreatePostAction', | |
| 363 | method: 'POST', | |
| 364 | ||
| 365 | validations: { | |
| 366 | title: { | |
| 367 | rule: schema.string().min(5).max(200), | |
| 368 | message: 'Title must be between 5 and 200 characters.', | |
| 369 | }, | |
| 370 | content: { | |
| 371 | rule: schema.string().min(10), | |
| 372 | message: 'Content must be at least 10 characters.', | |
| 373 | }, | |
| 374 | tags: { | |
| 375 | rule: schema.array().min(1).max(5).optional(), | |
| 376 | message: 'You can add between 1 and 5 tags.', | |
| 377 | }, | |
| 378 | published: { | |
| 379 | rule: schema.boolean().optional(), | |
| 380 | message: 'Published must be a boolean.', | |
| 381 | }, | |
| 382 | }, | |
| 383 | ||
| 384 | async handle(request: RequestInstance) { | |
| 385 | // Validation happens automatically before handle() is called | |
| 386 | // If validation fails, a 422 response is returned | |
| 387 | ||
| 388 | const title = request.get('title') | |
| 389 | const content = request.get('content') | |
| 390 | const tags = request.get('tags', []) | |
| 391 | const published = request.get('published', false) | |
| 392 | ||
| 393 | // ... create post | |
| 394 | }, | |
| 395 | }) | |
| 396 | ``` | |
| 397 | ||
| 398 | ## Authentication | |
| 399 | ||
| 400 | Stacks includes built-in authentication with token-based auth. | |
| 401 | ||
| 402 | ### Configuration | |
| 403 | ||
| 404 | ```typescript | |
| 405 | // config/auth.ts | |
| 406 | export default { | |
| 407 | default: 'api', | |
| 408 | ||
| 409 | guards: { | |
| 410 | api: { | |
| 411 | driver: 'token', | |
| 412 | provider: 'users', | |
| 413 | }, | |
| 414 | }, | |
| 415 | ||
| 416 | providers: { | |
| 417 | users: { | |
| 418 | driver: 'database', | |
| 419 | table: 'users', | |
| 420 | }, | |
| 421 | }, | |
| 422 | ||
| 423 | username: 'email', | |
| 424 | password: 'password', | |
| 425 | tokenExpiry: 30 * 24 * 60 * 60 * 1000, // 30 days | |
| 426 | tokenRotation: 24, // hours | |
| 427 | ||
| 428 | passwordReset: { | |
| 429 | expire: 60, // minutes | |
| 430 | throttle: 60, // seconds | |
| 431 | }, | |
| 432 | } | |
| 433 | ``` | |
| 434 | ||
| 435 | ### Login Action | |
| 436 | ||
| 437 | ```typescript | |
| 438 | // app/Actions/Auth/LoginAction.ts | |
| 439 | import type { RequestInstance } from '@stacksjs/types' | |
| 440 | import { Action } from '@stacksjs/actions' | |
| 441 | import { Auth } from '@stacksjs/auth' | |
| 442 | import { response } from '@stacksjs/router' | |
| 443 | import { schema } from '@stacksjs/validation' | |
| 444 | ||
| 445 | export default new Action({ | |
| 446 | name: 'LoginAction', | |
| 447 | description: 'Login to the application', | |
| 448 | method: 'POST', | |
| 449 | ||
| 450 | validations: { | |
| 451 | email: { | |
| 452 | rule: schema.string().email(), | |
| 453 | message: 'Email must be a valid email address.', | |
| 454 | }, | |
| 455 | password: { | |
| 456 | rule: schema.string().min(6).max(255), | |
| 457 | message: 'Password must be between 6 and 255 characters.', | |
| 458 | }, | |
| 459 | }, | |
| 460 | ||
| 461 | async handle(request: RequestInstance) { | |
| 462 | const email = request.get('email') | |
| 463 | const password = request.get('password') | |
| 464 | ||
| 465 | const result = await Auth.login({ email, password }) | |
| 466 | ||
| 467 | if (result) { | |
| 468 | return response.json({ | |
| 469 | token: result.token, | |
| 470 | user: { | |
| 471 | id: result.user?.id, | |
| 472 | email: result.user?.email, | |
| 473 | name: result.user?.name, | |
| 474 | }, | |
| 475 | }) | |
| 476 | } | |
| 477 | ||
| 478 | return response.unauthorized('Incorrect email or password') | |
| 479 | }, | |
| 480 | }) | |
| 481 | ``` | |
| 482 | ||
| 483 | ### Protected Routes | |
| 484 | ||
| 485 | ```typescript | |
| 486 | // routes/api.ts | |
| 487 | import { route } from '@stacksjs/router' | |
| 488 | ||
| 489 | // Public routes | |
| 490 | route.post('/login', 'Actions/Auth/LoginAction') | |
| 491 | route.post('/register', 'Actions/Auth/RegisterAction') | |
| 492 | ||
| 493 | // Protected routes | |
| 494 | route.group({ middleware: 'auth' }, () => { | |
| 495 | route.get('/me', 'Actions/Auth/AuthUserAction') | |
| 496 | route.post('/logout', 'Actions/Auth/LogoutAction') | |
| 497 | route.get('/tokens', 'Actions/Auth/ListTokensAction') | |
| 498 | route.delete('/tokens/{id}', 'Actions/Auth/RevokeTokenAction') | |
| 499 | }) | |
| 500 | ``` | |
| 501 | ||
| 502 | ### Using Auth in Actions | |
| 503 | ||
| 504 | ```typescript | |
| 505 | // app/Actions/Auth/AuthUserAction.ts | |
| 506 | import type { RequestInstance } from '@stacksjs/types' | |
| 507 | import { Action } from '@stacksjs/actions' | |
| 508 | import { response } from '@stacksjs/router' | |
| 509 | ||
| 510 | export default new Action({ | |
| 511 | name: 'AuthUserAction', | |
| 512 | description: 'Get authenticated user', | |
| 513 | method: 'GET', | |
| 514 | ||
| 515 | async handle(request: RequestInstance) { | |
| 516 | // The auth middleware ensures user is authenticated | |
| 517 | const user = request.user() | |
| 518 | ||
| 519 | return response.json({ | |
| 520 | id: user.id, | |
| 521 | email: user.email, | |
| 522 | name: user.name, | |
| 523 | }) | |
| 524 | }, | |
| 525 | }) | |
| 526 | ``` | |
| 527 | ||
| 528 | ## Database Queries | |
| 529 | ||
| 530 | Stacks provides an ORM and query builder for database operations. | |
| 531 | ||
| 532 | ### Models | |
| 533 | ||
| 534 | ```typescript | |
| 535 | // app/Models/User.ts | |
| 536 | import { Model } from '@stacksjs/orm' | |
| 537 | ||
| 538 | export default class User extends Model { | |
| 539 | static table = 'users' | |
| 540 | ||
| 541 | // Define fillable fields | |
| 542 | static fillable = ['email', 'name', 'password'] | |
| 543 | ||
| 544 | // Define hidden fields (excluded from JSON) | |
| 545 | static hidden = ['password'] | |
| 546 | ||
| 547 | // Relationships | |
| 548 | posts() { | |
| 549 | return this.hasMany(Post) | |
| 550 | } | |
| 551 | ||
| 552 | profile() { | |
| 553 | return this.hasOne(Profile) | |
| 554 | } | |
| 555 | } | |
| 556 | ``` | |
| 557 | ||
| 558 | ### Basic Queries | |
| 559 | ||
| 560 | ```typescript | |
| 561 | // Find by ID | |
| 562 | const user = await User.find(1) | |
| 563 | ||
| 564 | // Find or fail (throws if not found) | |
| 565 | const user = await User.findOrFail(1) | |
| 566 | ||
| 567 | // Find by column | |
| 568 | const user = await User.where('email', 'user@example.com').first() | |
| 569 | ||
| 570 | // Get all | |
| 571 | const users = await User.all() | |
| 572 | ||
| 573 | // With conditions | |
| 574 | const activeUsers = await User.where('status', 'active') | |
| 575 | .orderBy('created*at', 'desc') | |
| 576 | .get() | |
| 577 | ||
| 578 | // Create | |
| 579 | const user = await User.create({ | |
| 580 | email: 'new@example.com', | |
| 581 | name: 'New User', | |
| 582 | password: hashedPassword, | |
| 583 | }) | |
| 584 | ||
| 585 | // Update | |
| 586 | await user.update({ name: 'Updated Name' }) | |
| 587 | ||
| 588 | // Delete | |
| 589 | await user.delete() | |
| 590 | ``` | |
| 591 | ||
| 592 | ### Query Builder | |
| 593 | ||
| 594 | ```typescript | |
| 595 | import { DB } from '@stacksjs/database' | |
| 596 | ||
| 597 | // Raw queries | |
| 598 | const users = await DB.table('users') | |
| 599 | .select('id', 'name', 'email') | |
| 600 | .where('status', 'active') | |
| 601 | .orderBy('name') | |
| 602 | .limit(10) | |
| 603 | .get() | |
| 604 | ||
| 605 | // Joins | |
| 606 | const posts = await DB.table('posts') | |
| 607 | .join('users', 'posts.user*id', '=', 'users.id') | |
| 608 | .select('posts.*', 'users.name as author') | |
| 609 | .get() | |
| 610 | ||
| 611 | // Aggregates | |
| 612 | const count = await DB.table('users').count() | |
| 613 | const total = await DB.table('orders').sum('amount') | |
| 614 | const avg = await DB.table('products').avg('price') | |
| 615 | ``` | |
| 616 | ||
| 617 | ### Pagination | |
| 618 | ||
| 619 | ```typescript | |
| 620 | // In a controller or action | |
| 621 | async index(request: RequestInstance) { | |
| 622 | const page = request.query('page', 1) | |
| 623 | const perPage = request.query('per*page', 15) | |
| 624 | ||
| 625 | const users = await User.paginate(page, perPage) | |
| 626 | ||
| 627 | return response.json({ | |
| 628 | data: users.data, | |
| 629 | meta: { | |
| 630 | current*page: users.currentPage, | |
| 631 | per*page: users.perPage, | |
| 632 | total: users.total, | |
| 633 | last*page: users.lastPage, | |
| 634 | }, | |
| 635 | }) | |
| 636 | } | |
| 637 | ``` | |
| 638 | ||
| 639 | ## Response Helpers | |
| 640 | ||
| 641 | Stacks provides various response helpers: | |
| 642 | ||
| 643 | ```typescript | |
| 644 | import { response } from '@stacksjs/router' | |
| 645 | ||
| 646 | // JSON response | |
| 647 | response.json({ data: 'value' }) | |
| 648 | response.json({ data: 'value' }, 201) // with status code | |
| 649 | ||
| 650 | // Text response | |
| 651 | response.text('Hello, World!') | |
| 652 | ||
| 653 | // Error responses | |
| 654 | response.error('Something went wrong') | |
| 655 | response.error('Something went wrong', 500) | |
| 656 | ||
| 657 | // Common HTTP status responses | |
| 658 | response.notFound('Resource not found') | |
| 659 | response.unauthorized('Please login') | |
| 660 | response.forbidden('Access denied') | |
| 661 | response.badRequest('Invalid request') | |
| 662 | ||
| 663 | // Redirect | |
| 664 | response.redirect('/new-location') | |
| 665 | ||
| 666 | // No content | |
| 667 | response.noContent() | |
| 668 | ``` | |
| 669 | ||
| 670 | ## Complete Example: Blog API | |
| 671 | ||
| 672 | Let us build a complete blog API: | |
| 673 | ||
| 674 | ```typescript | |
| 675 | // routes/api.ts | |
| 676 | import { route } from '@stacksjs/router' | |
| 677 | ||
| 678 | // Public routes | |
| 679 | route.get('/posts', 'Actions/Blog/ListPostsAction') | |
| 680 | route.get('/posts/{slug}', 'Actions/Blog/GetPostAction') | |
| 681 | ||
| 682 | // Protected routes | |
| 683 | route.group({ middleware: 'auth' }, () => { | |
| 684 | route.post('/posts', 'Actions/Blog/CreatePostAction') | |
| 685 | route.put('/posts/{id}', 'Actions/Blog/UpdatePostAction') | |
| 686 | route.delete('/posts/{id}', 'Actions/Blog/DeletePostAction') | |
| 687 | }) | |
| 688 | ``` | |
| 689 | ||
| 690 | ```typescript | |
| 691 | // app/Actions/Blog/CreatePostAction.ts | |
| 692 | import type { RequestInstance } from '@stacksjs/types' | |
| 693 | import { Action } from '@stacksjs/actions' | |
| 694 | import { response } from '@stacksjs/router' | |
| 695 | import { schema } from '@stacksjs/validation' | |
| 696 | import { slugify } from '@stacksjs/strings' | |
| 697 | ||
| 698 | export default new Action({ | |
| 699 | name: 'CreatePostAction', | |
| 700 | description: 'Create a new blog post', | |
| 701 | method: 'POST', | |
| 702 | ||
| 703 | validations: { | |
| 704 | title: { | |
| 705 | rule: schema.string().min(5).max(200), | |
| 706 | message: 'Title must be between 5 and 200 characters.', | |
| 707 | }, | |
| 708 | content: { | |
| 709 | rule: schema.string().min(50), | |
| 710 | message: 'Content must be at least 50 characters.', | |
| 711 | }, | |
| 712 | excerpt: { | |
| 713 | rule: schema.string().max(500).optional(), | |
| 714 | message: 'Excerpt must be at most 500 characters.', | |
| 715 | }, | |
| 716 | tags: { | |
| 717 | rule: schema.array().max(10).optional(), | |
| 718 | message: 'Maximum 10 tags allowed.', | |
| 719 | }, | |
| 720 | }, | |
| 721 | ||
| 722 | async handle(request: RequestInstance) { | |
| 723 | const user = request.user() | |
| 724 | const title = request.get('title') | |
| 725 | const content = request.get('content') | |
| 726 | const excerpt = request.get('excerpt', '') | |
| 727 | const tags = request.get('tags', []) | |
| 728 | ||
| 729 | const post = await Post.create({ | |
| 730 | title, | |
| 731 | slug: slugify(title), | |
| 732 | content, | |
| 733 | excerpt: excerpt || content.substring(0, 200), | |
| 734 | author*id: user.id, | |
| 735 | published*at: null, | |
| 736 | }) | |
| 737 | ||
| 738 | // Attach tags | |
| 739 | if (tags.length > 0) { | |
| 740 | await post.tags().attach(tags) | |
| 741 | } | |
| 742 | ||
| 743 | return response.json({ | |
| 744 | message: 'Post created successfully', | |
| 745 | post: { | |
| 746 | id: post.id, | |
| 747 | title: post.title, | |
| 748 | slug: post.slug, | |
| 749 | excerpt: post.excerpt, | |
| 750 | author: user.name, | |
| 751 | }, | |
| 752 | }, 201) | |
| 753 | }, | |
| 754 | }) | |
| 755 | ``` | |
| 756 | ||
| 757 | ```typescript | |
| 758 | // app/Actions/Blog/ListPostsAction.ts | |
| 759 | import type { RequestInstance } from '@stacksjs/types' | |
| 760 | import { Action } from '@stacksjs/actions' | |
| 761 | import { response } from '@stacksjs/router' | |
| 762 | ||
| 763 | export default new Action({ | |
| 764 | name: 'ListPostsAction', | |
| 765 | description: 'List all published blog posts', | |
| 766 | method: 'GET', | |
| 767 | ||
| 768 | async handle(request: RequestInstance) { | |
| 769 | const page = request.query('page', 1) | |
| 770 | const perPage = request.query('per*page', 10) | |
| 771 | const tag = request.query('tag') | |
| 772 | ||
| 773 | let query = Post.where('published*at', '!=', null) | |
| 774 | .with('author', 'tags') | |
| 775 | .orderBy('published*at', 'desc') | |
| 776 | ||
| 777 | if (tag) { | |
| 778 | query = query.whereHas('tags', (q) => q.where('slug', tag)) | |
| 779 | } | |
| 780 | ||
| 781 | const posts = await query.paginate(page, perPage) | |
| 782 | ||
| 783 | return response.json({ | |
| 784 | data: posts.data.map(post => ({ | |
| 785 | id: post.id, | |
| 786 | title: post.title, | |
| 787 | slug: post.slug, | |
| 788 | excerpt: post.excerpt, | |
| 789 | author: post.author.name, | |
| 790 | tags: post.tags.map(t => t.name), | |
| 791 | published*at: post.published*at, | |
| 792 | })), | |
| 793 | meta: { | |
| 794 | current*page: posts.currentPage, | |
| 795 | per*page: posts.perPage, | |
| 796 | total: posts.total, | |
| 797 | last*page: posts.lastPage, | |
| 798 | }, | |
| 799 | }) | |
| 800 | }, | |
| 801 | }) | |
| 802 | ``` | |
| 803 | ||
| 804 | ## Next Steps | |
| 805 | ||
| 806 | Now that you know how to build APIs with Stacks, continue to: | |
| 807 | ||
| 808 | - [Authentication How-To](/bootcamp/how-to/authentication) - Deep dive into authentication | |
| 809 | - [Testing How-To](/bootcamp/how-to/testing) - Test your API endpoints | |
| 810 | - [Deployment How-To](/bootcamp/how-to/deploy) - Deploy your API to production | |
| 811 | ||
| 812 | ## Related Documentation | |
| 813 | ||
| 814 | - [Routing Guide](/basics/routing) | |
| 815 | - [Actions Guide](/basics/actions) | |
| 816 | - [Validation Guide](/packages/validation) | |
| 817 | - [Database Guide](/packages/database) | |
| 818 | - [Authentication Guide](/guide/auth) | |