🌐 Web Development

REST API

Representational State Transfer

An API design style that uses HTTP methods (GET, POST, PUT, DELETE). Statelessness is a core principle.

πŸ“– Detailed Explanation

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.

πŸ’» Code Example

Express.js REST API
// 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'));
fetch API client
// 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' }),
};

πŸ—£οΈ Examples of Practical Conversations

πŸ’Ό API Design Meeting
"How should we design the order cancellation API? Would DELETE /orders/{id} work?"

"Cancellation is not a deletion but a state change. It's RESTful to change the status to 'cancelled' with PATCH /orders/{id}, or to use an action endpoint like POST /orders/{id}/cancel. Use DELETE only when you are deleting the data itself."
πŸ” Code Review
"I'm trying to put a body in a GET request to send complex search conditions."

"Putting a body in a GET request is not recommended by the HTTP specification, and some clients or proxies may ignore it. For complex searches, create a POST /users/search endpoint, or consider GraphQL. If the query parameters get too long, you may also hit URL length limits."
πŸ“± Technical interview
"Can you explain the difference between PUT and PATCH in a REST API?"

"PUT is an idempotent operation that replaces the entire resource. Sending the same request multiple times gives the same result. PATCH is a partial update, so you only need to send the fields you want to change. For example, when changing only a user's email, PUT requires sending the entire user data, but with PATCH you only need to send the email field."

Take a mock interview on this topic β†’ WIA SOOM AI Interview Β· Start for free

⚠️ Cautions

  • Avoid verb-based URLs - Instead of /getUsers and /createUser, use /users and express the action with the HTTP method. URLs should represent only resources (nouns).
  • Use appropriate status codes - Do not send every response as 200 and put the error in the body. Use meaningful status codes such as 400, 401, 403, 404, and 500 so that clients can handle them appropriately.
  • Versioning is essential - Introduce versioning such as /api/v1/ and /api/v2/ from the start, so that existing clients do not break when the API changes.

πŸ”— Related Terms

πŸ“š Learn More