Hello World API
import { Card, CardContent, CardHeader, CardTitle } from β@astrojs/starlight/componentsβ; import { Tabs } from β@astrojs/starlight/componentsβ;
Hello World API
Section titled βHello World APIβA comprehensive Hello World API example that demonstrates the fundamental features of Veloce-TS framework.
Overview
Section titled βOverviewβThis example showcases the core capabilities of Veloce-TS through a simple but feature-rich API that includes:
- Decorator-based routing with
@Controller,@Get,@Post - Request validation using Zod schemas
- Query parameter extraction with the
@Querydecorator - Path parameters with
@Param - Request body validation with
@Body - OpenAPI documentation generation
- TypeScript support with full type safety
Features Demonstrated
Section titled βFeatures Demonstratedβπ― Core Decorators
Section titled βπ― Core Decoratorsβ@Controller('/hello')- Defines the controller base path@Get('/')- HTTP GET endpoint@Get('/:name')- Path parameter extraction@Post('/')- HTTP POST endpoint with body validation
π Parameter Handling
Section titled βπ Parameter Handlingβ@Param('name')- Extracts path parameters@Query()- Extracts query parameters (NEW in v0.2.6)@Body(Schema)- Validates request body with Zod
π Documentation
Section titled βπ Documentationβ@ApiDoc()- Adds OpenAPI documentation- Automatic schema generation
- Interactive API documentation
Project Structure
Section titled βProject Structureβhello_world/βββ src/β βββ controllers/β β βββ hello.controller.ts # Main controllerβ βββ index.ts # Application entry pointβββ public/β βββ docs.html # API documentationβββ package.jsonβββ tsconfig.jsonβββ README.mdAPI Endpoints
Section titled βAPI Endpointsβ1. Simple Hello World
Section titled β1. Simple Hello WorldβGET /helloResponse:
{ "message": "Hello World!", "timestamp": "2025-10-15T19:12:09.119Z", "version": "1.0.0"}2. Personalized Greeting
Section titled β2. Personalized GreetingβGET /hello/:name?language=es&format=textParameters:
name(path): The name to greetlanguage(query): Language for greeting (en,es,fr)format(query): Response format (json,text)
Examples:
GET /hello/Alfredoβ"Hello, Alfredo!"GET /hello/Alfredo?language=esβ"Β‘Hola, Alfredo!"GET /hello/Alfredo?language=fr&format=textβ"Bonjour, Alfredo!"
3. Create Custom Greeting
Section titled β3. Create Custom GreetingβPOST /helloContent-Type: application/json
{ "name": "World", "message": "Custom greeting", "language": "en"}4. List All Greetings
Section titled β4. List All GreetingsβGET /hello/greetings5. Get Greeting by ID
Section titled β5. Get Greeting by IDβGET /hello/greetings/:id6. API Information
Section titled β6. API InformationβGET /hello/api/infoKey Code Examples
Section titled βKey Code ExamplesβController Setup
Section titled βController Setupβimport { Controller, Get, Post, Body, Param, Query, ApiDoc} from 'veloce-ts';import { z } from 'zod';
const GreetingSchema = z.object({ name: z.string().min(1, 'Name is required').max(50, 'Name too long'), message: z.string().optional(), language: z.enum(['en', 'es', 'fr']).optional().default('en'),});
@Controller('/hello')export class HelloController { private greetings: any[] = [];
@Get('/') @ApiDoc({ summary: 'Say Hello World', description: 'Returns a simple hello message' }) async hello() { return { message: 'Hello World!', timestamp: new Date().toISOString(), version: '1.0.0' }; }
@Get('/:name') @ApiDoc({ summary: 'Say Hello to someone', description: 'Returns a personalized greeting message' }) async helloName( @Param('name') name: string, @Query() query: any ) { const language = query?.language || 'en'; const format = query?.format || 'json';
const greeting = this.getGreeting(name, language);
if (format === 'text') { return greeting; }
return { message: greeting, name: name, language: language, timestamp: new Date().toISOString(), format: format }; }
@Post('/') @ApiDoc({ summary: 'Create a custom greeting', description: 'Store a custom greeting message' }) async createGreeting(@Body(GreetingSchema) greeting: any) { const newGreeting = { ...greeting, id: this.greetings.length + 1, createdAt: new Date().toISOString() };
this.greetings.push(newGreeting);
return { message: 'Greeting created successfully', id: newGreeting.id, greeting: newGreeting }; }
private getGreeting(name: string, language: string = 'en'): string { const greetings = { en: `Hello, ${name}!`, es: `Β‘Hola, ${name}!`, fr: `Bonjour, ${name}!` };
return greetings[language as keyof typeof greetings] || greetings.en; }}import 'reflect-metadata';import { VeloceTS } from 'veloce-ts';import { HelloController } from './controllers/hello.controller';
const app = new VeloceTS({ title: 'Veloce-TS Hello World API', version: '1.0.0', description: 'A simple Hello World API demonstrating Veloce-TS basics'});
// Enable CORS for all originsapp.use('*', (c, next) => { c.header('Access-Control-Allow-Origin', '*'); c.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS'); c.header('Access-Control-Allow-Headers', 'Content-Type, Authorization'); return next();});
// Serve static filesapp.static('/public', './public');
// Include OpenAPI plugin for documentationapp.install('openapi');
// Include controllersapp.include(HelloController);
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => { console.log('π Veloce-TS Hello World API is running!'); console.log(''); console.log('ββββββββββββββββββββββββββββββββββββββββββββββββββ'); console.log(`π Server: http://localhost:${PORT}`); console.log(`π API Docs: http://localhost:${PORT}/docs.html`); console.log(`π OpenAPI Spec: http://localhost:${PORT}/openapi.json`); console.log('ββββββββββββββββββββββββββββββββββββββββββββββββββ'); console.log(''); console.log('π‘ Try these endpoints:'); console.log(' β’ GET /hello'); console.log(' β’ GET /hello/:name'); console.log(' β’ POST /hello'); console.log(' β’ GET /api/info'); console.log(''); console.log('π Happy coding!');});Whatβs New in v0.2.6
Section titled βWhatβs New in v0.2.6βThis example demonstrates the fixed @Query decorator that now works correctly:
Before (v0.2.5 and earlier):
Section titled βBefore (v0.2.5 and earlier):β// Had to use @Ctx() to manually extract query parametersasync helloName(@Param('name') name: string, @Ctx() c: any) { const query = c.req.query(); const language = query?.language || 'en';}Now (v0.2.6):
Section titled βNow (v0.2.6):β// Clean and simple with @Query() decoratorasync helloName(@Param('name') name: string, @Query() query: any) { const language = query?.language || 'en';}Quick Start
Section titled βQuick Startβ-
Create a new project:
Terminal window bun veloce-ts new hello_world --template restcd hello_world -
Install dependencies:
Terminal window bun install -
Replace the generated controller with the HelloController code above
-
Update package.json to use the latest version:
{"dependencies": {"veloce-ts": "^0.2.6"}} -
Run the server:
Terminal window bun run dev -
Test the API:
Terminal window # Simple hellocurl http://localhost:3000/hello# Personalized greeting in Spanishcurl "http://localhost:3000/hello/Alfredo?language=es"# Text format greeting in Frenchcurl "http://localhost:3000/hello/World?language=fr&format=text"
Learning Path
Section titled βLearning PathβThis example is perfect for:
- Beginners learning Veloce-TS fundamentals
- Understanding decorators and their usage
- Learning parameter extraction with
@Query,@Param,@Body - Exploring validation with Zod schemas
- Understanding OpenAPI documentation generation
Next Steps
Section titled βNext StepsβAfter mastering this example, explore:
- TaskMaster Example - Full-featured application with authentication, RBAC, and database
- Decorators Guide - Comprehensive decorator reference
- Dependency Injection - Advanced DI patterns
- Plugins Guide - Extending Veloce-TS functionality
API Documentation
Section titled βAPI DocumentationβOnce running, visit:
- Interactive Docs: http://localhost:3000/docs.html
- OpenAPI Spec: http://localhost:3000/openapi.json
This example provides a solid foundation for building more complex Veloce-TS applications!