RESTful API 설계
엣지 배포에 적합한 RESTful API 엔드포인트, 메서드 및 데이터 모델을 계획하고 구성합니다.
RESTful API 설계은(는) CoddyKit의 무료 Edge Computing with Cloudflare Workers & Deno 강의입니다. 이것은 3개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Edge Computing with Cloudflare Workers & Deno 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Edge Computing with Cloudflare Workers & Deno 강의에는 총 3개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Intro to RESTful APIs
Welcome! In this lesson, you'll learn about RESTful APIs, a fundamental way to design web services. REST stands for Representational State Transfer.
Think of an API as a menu in a restaurant. You make a request (order food), and the kitchen (server) sends back a response (your meal). REST defines a set of rules for how this communication should happen over the internet.
Core REST Principles
RESTful APIs are built around a few core ideas:
- Resources: Everything is a 'resource' (e.g., a user, a product).
- Unique URIs: Each resource has a unique address (a URL or URI).
- Standard Methods: HTTP methods (GET, POST, PUT, DELETE) are used to perform actions on resources.
- Statelessness: Each request from a client to a server must contain all the information needed to understand the request. The server doesn't store client 'session' state between requests.
Resources Are Nouns
When designing your API, think about the 'things' your application manages. These 'things' are your resources.
For example, if you're building an e-commerce API, your resources might include:
/products/users/orders/categories
Notice how these are all plural nouns. This is a common and recommended practice in RESTful design.
HTTP Methods: The Verbs
HTTP methods tell the server what kind of action you want to perform on a resource. They are like verbs in a sentence:
- GET: Retrieve data (e.g., get a product, get a list of users).
- POST: Create new data (e.g., create a new user, add a new product).
- PUT: Update existing data (replaces an entire resource).
- PATCH: Partially update existing data (updates specific fields of a resource).
- DELETE: Remove data (e.g., delete a product).
GET: Fetching Data Example
The GET method is used to request data from a specified resource. It should never have side effects (i.e., it shouldn't change data on the server).
Try running this simple Deno server. Then open your browser to http://localhost:8000/products to see the output.
import { serve } from "https://deno.land/std/http/server.ts";
serve(async (req) => {
const url = new URL(req.url);
if (req.method === "GET" && url.pathname === "/products") {
const products = [
{ id: 1, name: "Wireless Mouse", price: 25.99 },
{ id: 2, name: "Mechanical Keyboard", price: 79.99 }
];
return new Response(JSON.stringify(products), {
headers: { "Content-Type": "application/json" }
});
}
return new Response("Not Found", { status: 404 });
}, { port: 8000 });
console.log("Server running on http://localhost:8000");POST: Creating Data Example
The POST method is used to submit an entity to the specified resource, often causing a change in state or the creation of a new resource.
This example shows how a Deno server can handle a POST request to create a new product. You would typically send JSON data in the request body.
import { serve } from "https://deno.land/std/http/server.ts";
serve(async (req) => {
const url = new URL(req.url);
if (req.method === "POST" && url.pathname === "/products") {
try {
const newProduct = await req.json();
// In a real application, you'd save newProduct to a database.
// For this example, we'll just log it and return a mock ID.
console.log("Received new product:", newProduct);
return new Response(JSON.stringify({ ...newProduct, id: 3 }), {
status: 201, // 201 Created
headers: { "Content-Type": "application/json" }
});
} catch (e) {
return new Response("Invalid JSON payload", { status: 400 });
}
}
return new Response("Method Not Allowed", { status: 405 });
}, { port: 8000 });
console.log("Server running on http://localhost:8000");Designing Endpoint Paths
Clear and consistent endpoint paths (URIs) are crucial for a good API. Here are some best practices:
- Use plural nouns:
/users, not/user. - Avoid verbs in paths:
/productsis good,/getProductsis not. The HTTP method implies the action. - Nesting for relationships: For related resources, use nesting. E.g.,
/users/{id}/ordersto get orders for a specific user. - Use path parameters for specific resources:
/products/{id}to refer to a single product.
Data Models & Payloads
The data you send to and receive from your API is called a payload. In modern RESTful APIs, JSON (JavaScript Object Notation) is the standard format.
A data model defines the structure of this JSON. For example, a 'product' data model might look like this:
{
"id": 123,
"name": "Example Product",
"description": "A great item.",
"price": 19.99
}Consistency in your data models makes your API predictable and easier to use.
RESTful APIs at the Edge
RESTful API design is particularly well-suited for edge computing environments like Cloudflare Workers:
- Statelessness: Edge functions are often short-lived and don't maintain state, aligning perfectly with REST's stateless principle.
- Caching: GET requests are easily cacheable by CDNs, which is a core benefit of edge computing for reducing latency.
- Distributed Nature: REST's clear separation of concerns and uniform interface makes it easier to distribute logic across many edge locations.
API Design Check
You're building an API for a blog. You need to retrieve a list of all blog posts. Which of the following API endpoint designs and HTTP methods is the most RESTful?
Recap: RESTful API Design
Great job! You've learned the fundamentals of designing RESTful APIs:
- APIs use resources (nouns) and HTTP methods (verbs) for communication.
- Common methods are GET (retrieve), POST (create), PUT/PATCH (update), and DELETE (remove).
- Endpoint paths should be clear, using plural nouns and avoiding verbs.
- JSON is the standard format for data payloads.
- REST's principles make it an excellent choice for edge computing due to statelessness and cacheability.
Next, we'll dive into input validation and security for your edge APIs!
자주 묻는 질문
“RESTful API 설계” 강의는 무료인가요?
네 — “RESTful API 설계” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Edge Computing with Cloudflare Workers & Deno 강의 전체를 잠금 해제할 수 있습니다. Edge Computing with Cloudflare Workers & Deno 강의에는 총 3개의 강의가 포함되어 있습니다.
“RESTful API 설계”에서 뭘 배우나요?
엣지 배포에 적합한 RESTful API 엔드포인트, 메서드 및 데이터 모델을 계획하고 구성합니다. 브라우저에서 직접 실행하는 실습 코드로 Edge Computing with Cloudflare Workers & Deno을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Edge Computing with Cloudflare Workers & Deno을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Edge Computing with Cloudflare Workers & Deno은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 3개 중 1번째 강의입니다.
“RESTful API 설계” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Edge Computing with Cloudflare Workers & Deno 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Edge Computing with Cloudflare Workers & Deno 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- RESTful API 설계
- 라우팅 및 미들웨어
- 검증 및 오류 처리