1. 프로젝트 생성
터미널
mkdir my-api && cd my-api
npm init -y
npm install hono @hono/node-server
npm install -D typescript @types/node tsx tsx는 TypeScript를 바로 실행할 수 있게 해줍니다.
2. 첫 API 작성
src/index.ts
import { Hono } from 'hono';
import { serve } from '@hono/node-server';
const app = new Hono();
// Health check
app.get('/health', (c) => {
return c.json({
status: 'ok',
timestamp: new Date().toISOString(),
});
});
// Hello API
app.get('/api/hello', (c) => {
const name = c.req.query('name') || 'World';
return c.json({ message: `Hello, ${name}!` });
});
// 서버 시작
serve({ fetch: app.fetch, port: 8000 });
console.log('🚀 Server running on http://localhost:8000');실행
터미널
npx tsx src/index.ts
# 테스트
curl http://localhost:8000/health
curl http://localhost:8000/api/hello?name=Choorai3. CRUD API 추가
src/index.ts
import { Hono } from 'hono';
import { serve } from '@hono/node-server';
import { cors } from 'hono/cors';
const app = new Hono();
// CORS 설정
app.use('*', cors({
origin: ['http://localhost:5173'],
credentials: true,
}));
// 인메모리 저장소
interface Project {
id: string;
name: string;
description: string | null;
created_at: string;
}
const projects = new Map<string, Project>();
// 프로젝트 목록
app.get('/api/v1/projects', (c) => {
const items = Array.from(projects.values());
return c.json({ items, total: items.length });
});
// 프로젝트 생성
app.post('/api/v1/projects', async (c) => {
const body = await c.req.json();
const project: Project = {
id: crypto.randomUUID(),
name: body.name,
description: body.description || null,
created_at: new Date().toISOString(),
};
projects.set(project.id, project);
return c.json(project, 201);
});
// 프로젝트 조회
app.get('/api/v1/projects/:id', (c) => {
const project = projects.get(c.req.param('id'));
if (!project) return c.json({ error: 'Not found' }, 404);
return c.json(project);
});
// 프로젝트 삭제
app.delete('/api/v1/projects/:id', (c) => {
const deleted = projects.delete(c.req.param('id'));
if (!deleted) return c.json({ error: 'Not found' }, 404);
return c.body(null, 204);
});
serve({ fetch: app.fetch, port: 8000 });
console.log('🚀 Server running on http://localhost:8000');4. Docker로 배포
Dockerfile
FROM node:20-slim
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
RUN npm run build
EXPOSE 8000
CMD ["node", "dist/index.js"]터미널
# 로컬 테스트
docker build -t my-hono-api .
docker run -p 8000:8000 my-hono-api
# Cloud Run 배포
gcloud builds submit --tag gcr.io/YOUR_PROJECT/my-hono-api
gcloud run deploy my-hono-api --image gcr.io/YOUR_PROJECT/my-hono-apiFastAPI vs Hono
Hono (이 페이지)
- ✅ JavaScript/TypeScript 통일
- ✅ 프론트엔드와 같은 언어
- ✅ Edge Runtime 지원
- ⚠️ 타입 검증 직접 구현
FastAPI (Lv.2)
- ✅ 자동 문서화 (Swagger)
- ✅ Pydantic 타입 검증
- ✅ Python 생태계 (ML/AI)
- ⚠️ 별도 언어 학습 필요
전체 예제 코드
B2B Admin API의 Hono 버전을 확인하세요: examples/b2b-admin/api-hono