RESTful API와 WebSockets
동적 업데이트를 위해 WebSockets가 기존 REST API를 보완하는 하이브리드 아키텍처를 설계합니다.
RESTful API와 WebSockets은(는) CoddyKit의 무료 WebSockets & Realtime Systems Programming 강의입니다. 이것은 3개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 WebSockets & Realtime Systems Programming 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. WebSockets & Realtime Systems Programming 강의에는 총 3개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Why Hybrid Architectures?
Welcome! In this lesson, we'll explore how to combine two powerful web communication tools: RESTful APIs and WebSockets.
While both facilitate communication, they excel in different areas. A hybrid approach leverages their individual strengths to build robust, dynamic applications.
- REST for initial data loading and traditional resource management.
- WebSockets for instant, real-time data updates.
RESTful APIs: The Foundation
RESTful APIs are a cornerstone of modern web development. They follow a request-response model, typically over HTTP.
Think of them as ordering from a menu: you make a specific request (e.g., "Get me all products"), and the server responds with the data. They are great for:
- Fetching static or infrequently changing data.
- Performing one-time actions (creating, updating, deleting resources).
- Initial page loads with existing information.
WebSockets: Real-time Dynamics
WebSockets, as you've learned, provide a persistent, full-duplex connection. This means data can flow simultaneously in both directions, without constant new requests.
They are like a live chat: once connected, messages can be sent back and forth instantly. This makes them perfect for:
- Live data feeds (stock prices, sports scores).
- Real-time notifications (new messages, activity alerts).
- Collaborative applications (document editing).
Complementary, Not Competing
It's important to see REST and WebSockets as complementary tools, not competitors. They solve different problems efficiently.
Combining them allows you to handle both traditional data operations and real-time interactions within the same application, leading to a richer user experience.
A well-designed hybrid system uses each protocol where it makes the most sense.
The Hybrid Workflow
A common hybrid workflow looks like this:
- Client loads: Makes initial requests via REST to fetch existing data (e.g., a list of items).
- Client connects: Establishes a WebSocket connection for real-time updates related to that data.
- Server updates: Pushes new data or changes via WebSocket as they occur.
- Client interacts: Might use REST for specific resource actions (e.g., 'mark item as complete') and receive confirmation/updates via WebSocket.
Server: REST Endpoint for Data
First, let's set up a simple Node.js server with an Express REST endpoint. This endpoint will serve our initial list of 'items'.
This demonstrates how a client would initially fetch existing data. (Remember to npm install express)
const express = require('express');
const app = express();
const PORT = 3000;
let items = [
{ id: 1, name: 'Item A', status: 'pending' },
{ id: 2, name: 'Item B', status: 'completed' }
];
// REST endpoint to get all items
app.get('/api/items', (req, res) => {
res.json(items);
});
app.listen(PORT, () => {
console.log(`REST server listening on port ${PORT}`);
});
Server: Adding WebSocket Updates
Now, let's extend our server to include a WebSocket. This WebSocket will push real-time updates whenever an item's status changes.
We use the ws library and integrate it with our existing Express server. (Remember to npm install ws)
const express = require('express');
const WebSocket = require('ws');
const http = require('http');
const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });
const PORT = 3000;
let items = [
{ id: 1, name: 'Item A', status: 'pending' },
{ id: 2, name: 'Item B', status: 'completed' }
];
// REST endpoint to get all items
app.get('/api/items', (req, res) => {
res.json(items);
});
// WebSocket connection handling
wss.on('connection', ws => {
console.log('Client connected via WebSocket');
// Simulate an item update every 5 seconds
const interval = setInterval(() => {
const itemToUpdate = items[Math.floor(Math.random() * items.length)];
itemToUpdate.status = itemToUpdate.status === 'pending' ? 'completed' : 'pending';
const updateMessage = JSON.stringify({ type: 'itemUpdate', item: itemToUpdate });
wss.clients.forEach(client => {
if (client.readyState === WebSocket.OPEN) {
client.send(updateMessage);
}
});
}, 5000);
ws.on('close', () => {
console.log('Client disconnected');
clearInterval(interval);
});
});
server.listen(PORT, () => {
console.log(`Hybrid server listening on port ${PORT}`);
});
Client: Fetching Initial Data (JS)
On the client-side (e.g., in a web browser), you'd first use fetch or XMLHttpRequest to get the initial list of items from the REST API.
This ensures the user sees existing data immediately.
async function getInitialItems() {
try {
const response = await fetch('http://localhost:3000/api/items');
const data = await response.json();
console.log('Initial items (REST):', data);
// Render initial items on the UI
} catch (error) {
console.error('Error fetching items:', error);
}
}
getInitialItems();
Client: Subscribing to Live Updates (JS)
After fetching initial data, the client opens a WebSocket connection to receive real-time updates. When a message arrives, it can update the UI dynamically.
This keeps the displayed data fresh without constant page refreshes.
const ws = new WebSocket('ws://localhost:3000');
ws.onopen = () => {
console.log('WebSocket connected!');
};
ws.onmessage = event => {
const message = JSON.parse(event.data);
if (message.type === 'itemUpdate') {
console.log('Real-time item update:', message.item);
// Update the specific item on the UI
}
};
ws.onclose = () => {
console.log('WebSocket disconnected.');
};
ws.onerror = error => {
console.error('WebSocket error:', error);
};
Hybrid Use Cases
Which communication method is best for each scenario in a hybrid application?
Recap: Best of Both Worlds
You've learned how to design hybrid architectures that combine RESTful APIs and WebSockets.
- REST excels for initial data loading and traditional CRUD operations due to its stateless, request-response nature.
- WebSockets are perfect for instant, bidirectional communication, providing dynamic updates and real-time interactions.
By strategically using both, you can build performant and highly interactive applications. Next, we'll look at bridging WebSockets to message queues.
자주 묻는 질문
“RESTful API와 WebSockets” 강의는 무료인가요?
네 — “RESTful API와 WebSockets” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 WebSockets & Realtime Systems Programming 강의 전체를 잠금 해제할 수 있습니다. WebSockets & Realtime Systems Programming 강의에는 총 3개의 강의가 포함되어 있습니다.
“RESTful API와 WebSockets”에서 뭘 배우나요?
동적 업데이트를 위해 WebSockets가 기존 REST API를 보완하는 하이브리드 아키텍처를 설계합니다. 브라우저에서 직접 실행하는 실습 코드로 WebSockets & Realtime Systems Programming을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
WebSockets & Realtime Systems Programming을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 WebSockets & Realtime Systems Programming은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 3개 중 1번째 강의입니다.
“RESTful API와 WebSockets” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 WebSockets & Realtime Systems Programming 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 WebSockets & Realtime Systems Programming 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- RESTful API와 WebSockets
- 메시지 큐 연결
- 데이터베이스 변경 사항을 클라이언트에 스트리밍하기