초보자 친화적인 Node.js를 사용한 첫 API 구축 가이드
Source: Dev.to
Introduction
백엔드 개발이 처음이라면 API를 만드는 것이 위협적으로 느껴질 수 있습니다.
좋은 소식 — Node.js와 Express를 사용하면 몇 분 안에 작동하는 API를 만들 수 있습니다.
What Is an API?
**API (Application Programming Interface)**는 서로 다른 애플리케이션이 서로 통신할 수 있게 해줍니다.
Example
- Frontend: “모든 사용자를 알려줘.”
- Backend API: “여기 있어요!”
Setting Up the Project
mkdir my-first-api
cd my-first-api
npm init -y
npm install express
Creating the Server
Create a file named server.js and add the following code:
const express = require('express');
const app = express();
app.use(express.json());
// Home route
app.get('/', (req, res) => {
res.send({ message: 'Welcome to your first Node.js API!' });
});
// Sample GET route
app.get('/api/users', (req, res) => {
res.send([
{ id: 1, name: 'John' },
{ id: 2, name: 'Sarah' }
]);
});
// In‑memory users array
let users = [
{ id: 1, name: 'John' },
{ id: 2, name: 'Sarah' }
];
// POST route to add a user
app.post('/api/users', (req, res) => {
const newUser = {
id: users.length + 1,
name: req.body.name
};
users.push(newUser);
res.status(201).send(newUser);
});
// Start server
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
Run the server:
node server.js
You should see:
Server running on http://localhost:3000
Running the API
브라우저를 열거나 curl 혹은 Postman 같은 도구를 사용해 엔드포인트와 상호작용하세요.
- Home:
http://localhost:3000 - Get users:
http://localhost:3000/api/users
Using curl
curl http://localhost:3000/api/users
Using Postman (POST)
{
"name": "Emily"
}
http://localhost:3000/api/users 로 요청을 보내면 새 사용자를 추가할 수 있습니다.
Next Steps
- Routing best practices – 라우트를 별도 모듈로 정리하기.
- Environment variables –
dotenv로 포트, DB 인증 정보 등 설정을 저장하기. - Database integration – 메모리 배열 대신 MongoDB, PostgreSQL 등과 연결하기.
- Authentication – 보호된 라우트를 위해 JWT 또는 세션 기반 인증 구현하기.
- Deployment – Heroku, Vercel, Render 같은 플랫폼에 배포하기.
멋진 시작입니다 — 계속 진행해 보세요! 🚀