REST API
Representational State Transfer
An API design style that uses HTTP methods (GET, POST, PUT, DELETE). Statelessness is a core principle.
Representational State Transfer
An API design style that uses HTTP methods (GET, POST, PUT, DELETE). Statelessness is a core principle.
REST API (Representational State Transfer) is an architectural style first proposed in Roy Fielding's 2000 doctoral dissertation, and it has become the de facto standard for web service design. It uses the methods of the HTTP protocol (GET, POST, PUT, DELETE, PATCH) to manipulate resources in a CRUD (Create, Read, Update, Delete) manner. The core of RESTful design is that URLs express resources as nouns, while HTTP methods indicate the actions.
REST has six constraints: client-server separation, statelessness, cacheability, a layered system, code on demand (optional), and a uniform interface. In particular, statelessness means that each request is independent and the server does not store the client's state. This makes it easy to scale servers and simplifies load balancing.
In RESTful API design, resource naming conventions are important. Plural nouns (/users), hierarchical relationships (/users/1/posts), and filtering through query parameters (/users?role=admin) are recommended. HTTP status codes should also be used meaningfully. Examples include 200 (success), 201 (created), 400 (bad request), 401 (authentication required), 404 (not found), and 500 (server error).
In modern API design, versioning (/api/v1/), pagination, HATEOAS (Hypermedia as the Engine of Application State), and OpenAPI (Swagger) documentation are important. Alternatives such as GraphQL and gRPC exist, but REST is still the most widely used because of its simplicity and its use of HTTP standards. API Gateway, Rate Limiting, and CORS configuration are also essential considerations in practice.
// Express.jsλ‘ RESTful API ꡬν
import express from 'express';
const app = express();
app.use(express.json());
interface User {
id: number;
name: string;
email: string;
}
let users: User[] = [
{ id: 1, name: 'νκΈΈλ', email: 'hong@example.com' },
{ id: 2, name: 'κΉμν¬', email: 'kim@example.com' },
];
// GET /users - μ 체 μ¬μ©μ λͺ©λ‘ μ‘°ν
app.get('/api/v1/users', (req, res) => {
const { role, limit = 10, offset = 0 } = req.query;
let result = users;
// νμ΄μ§λ€μ΄μ
μ μ©
result = result.slice(Number(offset), Number(offset) + Number(limit));
res.json({
data: result,
pagination: {
total: users.length,
limit: Number(limit),
offset: Number(offset),
}
});
});
// GET /users/:id - νΉμ μ¬μ©μ μ‘°ν
app.get('/api/v1/users/:id', (req, res) => {
const user = users.find(u => u.id === Number(req.params.id));
if (!user) {
return res.status(404).json({
error: 'Not Found',
message: `User with id ${req.params.id} not found`
});
}
res.json({ data: user });
});
// POST /users - μ μ¬μ©μ μμ±
app.post('/api/v1/users', (req, res) => {
const { name, email } = req.body;
// μ ν¨μ± κ²μ¬
if (!name || !email) {
return res.status(400).json({
error: 'Bad Request',
message: 'name and email are required'
});
}
const newUser: User = {
id: users.length + 1,
name,
email
};
users.push(newUser);
// 201 Createdμ Location ν€λ λ°ν
res.status(201)
.header('Location', `/api/v1/users/${newUser.id}`)
.json({ data: newUser });
});
// PUT /users/:id - μ 체 μ
λ°μ΄νΈ (Idempotent)
app.put('/api/v1/users/:id', (req, res) => {
const index = users.findIndex(u => u.id === Number(req.params.id));
if (index === -1) {
return res.status(404).json({ error: 'Not Found' });
}
const { name, email } = req.body;
users[index] = { id: Number(req.params.id), name, email };
res.json({ data: users[index] });
});
// PATCH /users/:id - λΆλΆ μ
λ°μ΄νΈ
app.patch('/api/v1/users/:id', (req, res) => {
const user = users.find(u => u.id === Number(req.params.id));
if (!user) {
return res.status(404).json({ error: 'Not Found' });
}
Object.assign(user, req.body);
res.json({ data: user });
});
// DELETE /users/:id - μμ
app.delete('/api/v1/users/:id', (req, res) => {
const index = users.findIndex(u => u.id === Number(req.params.id));
if (index === -1) {
return res.status(404).json({ error: 'Not Found' });
}
users.splice(index, 1);
// 204 No Content - λ³Έλ¬Έ μμ΄ μ±κ³΅ μλ΅
res.status(204).send();
});
// μλ¬ νΈλ€λ§ λ―Έλ€μ¨μ΄
app.use((err: Error, req: express.Request, res: express.Response, next: express.NextFunction) => {
console.error(err.stack);
res.status(500).json({
error: 'Internal Server Error',
message: process.env.NODE_ENV === 'development' ? err.message : 'Something went wrong'
});
});
app.listen(3000, () => console.log('API server running on port 3000'));
// REST API ν΄λΌμ΄μΈνΈ μ νΈλ¦¬ν°
const API_BASE = 'https://api.example.com/v1';
async function apiClient<T>(
endpoint: string,
options: RequestInit = {}
): Promise<T> {
const response = await fetch(`${API_BASE}${endpoint}`, {
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${getToken()}`,
...options.headers,
},
...options,
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.message || `HTTP ${response.status}`);
}
// 204 No Content μ²λ¦¬
if (response.status === 204) {
return null as T;
}
return response.json();
}
// CRUD μμ
const api = {
// Read
getUsers: () => apiClient<{ data: User[] }>('/users'),
getUser: (id: number) => apiClient<{ data: User }>(`/users/${id}`),
// Create
createUser: (data: Omit<User, 'id'>) =>
apiClient<{ data: User }>('/users', {
method: 'POST',
body: JSON.stringify(data),
}),
// Update
updateUser: (id: number, data: Partial<User>) =>
apiClient<{ data: User }>(`/users/${id}`, {
method: 'PATCH',
body: JSON.stringify(data),
}),
// Delete
deleteUser: (id: number) =>
apiClient<null>(`/users/${id}`, { method: 'DELETE' }),
};
Take a mock interview on this topic β WIA SOOM AI Interview Β· Start for free