RESTful API 엔드포인트 설계
REST의 핵심 원칙을 배우고 다양한 리소스를 위한 깔끔하고 효율적인 API 엔드포인트를 설계합니다.
RESTful API 엔드포인트 설계은(는) CoddyKit의 무료 Node.js Backend Development Bootcamp 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Node.js Backend Development Bootcamp 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Node.js Backend Development Bootcamp 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Intro to RESTful APIs
Welcome! In this lesson, we'll dive into designing clean and efficient API endpoints following REST principles. Understanding REST is crucial for building scalable web services.
REST stands for Representational State Transfer. It's an architectural style for networked applications, emphasizing a stateless client-server communication.
Resources: The Nouns of REST
At the heart of REST are resources. Think of resources as any information or data that your API can provide or manipulate. They are the 'things' your API manages.
- A resource is identified by a unique URL (Uniform Resource Locator).
- They are typically represented by nouns, like
users,products, ororders. - Ideally, use plural nouns for collections of resources.
Actions with HTTP Methods
While resources are nouns, the actions you perform on them are indicated by standard HTTP methods (also called verbs). These methods correspond directly to common data operations:
- GET: Retrieve data (Read)
- POST: Create new data (Create)
- PUT: Replace existing data (Update all)
- PATCH: Partially update existing data (Update partial)
- DELETE: Remove data (Delete)
Structuring Your API Endpoints
A well-designed endpoint URL should be intuitive and predictable. It typically follows a pattern:
/api/<version>/<resource_name>Using a version (like v1) is good practice for future API changes. Always use plural nouns for resource names.
- Good:
/api/v1/users - Bad:
/api/v1/getUsers
Collection and Item URLs
REST APIs distinguish between a collection of resources and a single resource within that collection:
- Collection URL: Refers to a group of resources. E.g.,
/users(all users). - Item URL: Refers to a specific resource. E.g.,
/users/123(user with ID 123).
The ID (:id in Express) is a unique identifier for that specific resource.
Speaking with Status Codes
HTTP status codes are crucial for your API to communicate the outcome of a request to the client. They tell the client if the request was successful, if there was an error, and why.
- 200 OK: Request successful.
- 201 Created: Resource successfully created.
- 204 No Content: Request successful, but no content to return (e.g., DELETE).
- 400 Bad Request: Client sent invalid data.
- 404 Not Found: Resource not found.
- 500 Internal Server Error: Server-side error.
User API Endpoint Design
Let's design endpoints for a User resource. Notice how HTTP methods and URLs combine to describe actions.
Try running this example to see the routes in action:
const express = require('express');
const app = express();
const port = 3000;
// Get all users
app.get('/api/v1/users', (req, res) => {
res.status(200).send('GET /api/v1/users: Retrieve all users');
});
// Create a new user
app.post('/api/v1/users', (req, res) => {
res.status(201).send('POST /api/v1/users: Create a new user');
});
// Get a specific user by ID
app.get('/api/v1/users/:id', (req, res) => {
res.status(200).send(`GET /api/v1/users/${req.params.id}: Retrieve user ${req.params.id}`);
});
// Update a specific user by ID
app.put('/api/v1/users/:id', (req, res) => {
res.status(200).send(`PUT /api/v1/users/${req.params.id}: Update user ${req.params.id}`);
});
// Delete a specific user by ID
app.delete('/api/v1/users/:id', (req, res) => {
res.status(204).send(`DELETE /api/v1/users/${req.params.id}: Delete user ${req.params.id}`);
});
app.listen(port, () => {
console.log(`User API running on http://localhost:${port}`);
});Product API Endpoint Design
Here's another example for a Product resource. The patterns remain consistent, making your API easy to understand and use for developers.
Run this code to see a product-focused API:
const express = require('express');
const app = express();
const port = 3001; // Using a different port
// Get all products
app.get('/api/v1/products', (req, res) => {
res.status(200).send('GET /api/v1/products: Retrieve all products');
});
// Create a new product
app.post('/api/v1/products', (req, res) => {
res.status(201).send('POST /api/v1/products: Create a new product');
});
// Get a specific product by ID
app.get('/api/v1/products/:id', (req, res) => {
res.status(200).send(`GET /api/v1/products/${req.params.id}: Retrieve product ${req.params.id}`);
});
// Delete a specific product by ID
app.delete('/api/v1/products/:id', (req, res) => {
res.status(204).send(`DELETE /api/v1/products/${req.params.id}: Delete product ${req.params.id}`);
});
app.listen(port, () => {
console.log(`Product API running on http://localhost:${port}`);
});Clean URL Best Practices
To ensure your API is user-friendly and maintainable, follow these best practices:
- Use Plural Nouns: For collections (e.g.,
/products, not/product). - Avoid Verbs in URLs: Let HTTP methods define actions (e.g.,
POST /users, not/createUser). - Use Hyphens: For readability in multi-word resource names (e.g.,
/order-items). - Keep URLs Simple: Avoid deep nesting; query parameters can handle filtering/sorting.
Test Your REST Knowledge
Which of the following endpoint designs correctly follows RESTful principles for creating a new product and retrieving a specific product?
Recap: Designing RESTful Endpoints
Great job! You've learned the fundamentals of designing RESTful API endpoints. Remember these key takeaways:
- Resources are the nouns, identified by URLs.
- HTTP Methods (GET, POST, PUT, DELETE) define actions.
- Use plural nouns for collections and specific IDs for items.
- Communicate outcomes using appropriate HTTP Status Codes.
- Strive for clean, predictable URLs for a user-friendly API.
This foundation will help you build robust and intuitive APIs!
자주 묻는 질문
“RESTful API 엔드포인트 설계” 강의는 무료인가요?
네 — “RESTful API 엔드포인트 설계” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Node.js Backend Development Bootcamp 강의 전체를 잠금 해제할 수 있습니다. Node.js Backend Development Bootcamp 강의에는 총 4개의 강의가 포함되어 있습니다.
“RESTful API 엔드포인트 설계”에서 뭘 배우나요?
REST의 핵심 원칙을 배우고 다양한 리소스를 위한 깔끔하고 효율적인 API 엔드포인트를 설계합니다. 브라우저에서 직접 실행하는 실습 코드로 Node.js Backend Development Bootcamp을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Node.js Backend Development Bootcamp을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Node.js Backend Development Bootcamp은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“RESTful API 엔드포인트 설계” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Node.js Backend Development Bootcamp 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Node.js Backend Development Bootcamp 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- Express.js 프레임워크 기초
- Express의 라우팅과 미들웨어
- RESTful API 엔드포인트 설계
- 요청 데이터 처리: 본문, 쿼리 및 매개변수