0Pricing
Edge Computing with Cloudflare Workers & Deno · บทเรียน

การออกแบบ API แบบ RESTful

วางแผนและจัดโครงสร้างจุดปลายทาง API เมธอด และแบบจำลองข้อมูลที่เหมาะกับการนำไปใช้งานใกล้ผู้ใช้

การออกแบบ API แบบ RESTful เป็นบทเรียน Edge Computing with Cloudflare Workers & Deno ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 3 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน 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: /products is good, /getProducts is not. The HTTP method implies the action.
  • Nesting for relationships: For related resources, use nesting. E.g., /users/{id}/orders to 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!

คำถามที่พบบ่อย

บทเรียน “การออกแบบ API แบบ RESTful” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การออกแบบ API แบบ RESTful” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Edge Computing with Cloudflare Workers & Deno ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Edge Computing with Cloudflare Workers & Deno มีบทเรียนทั้งหมด 3 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การออกแบบ API แบบ RESTful”

วางแผนและจัดโครงสร้างจุดปลายทาง API เมธอด และแบบจำลองข้อมูลที่เหมาะกับการนำไปใช้งานใกล้ผู้ใช้ คุณปฏิบัติ Edge Computing with Cloudflare Workers & Deno ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Edge Computing with Cloudflare Workers & Deno หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน Edge Computing with Cloudflare Workers & Deno บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 3 บทเรียน

บทเรียน “การออกแบบ API แบบ RESTful” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน Edge Computing with Cloudflare Workers & Deno นี้ได้ไหม

ได้ บทเรียน Edge Computing with Cloudflare Workers & Deno ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. การออกแบบ API แบบ RESTful
  2. การกำหนดเส้นทางและมิดเดิลแวร์
  3. การตรวจสอบความถูกต้องและการจัดการข้อผิดพลาด
← กลับไปที่ Edge Computing with Cloudflare Workers & Deno