0Pricing
FastAPI Backend Development Bootcamp · บทเรียน

การกำหนดเวอร์ชันด้วย URL ส่วนหัว และชนิดสื่อ

เปรียบเทียบแนวทางการกำหนดเวอร์ชันและจัดกลุ่มเส้นทางให้เป็นระเบียบ เพื่อให้ไคลเอ็นต์อัปเกรดได้โดยไม่เสียหาย

การกำหนดเวอร์ชันด้วย URL ส่วนหัว และชนิดสื่อ เป็นบทเรียน FastAPI Backend Development Bootcamp ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน FastAPI Backend Development Bootcamp และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส FastAPI Backend Development Bootcamp มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Why Version an API at All?

Once real clients depend on your API, you can no longer change a response shape freely. Renaming a field, removing a key, or changing a status code can break production apps you do not control.

Versioning lets you ship breaking changes under a new label while the old behavior keeps working. Clients upgrade on their own schedule.

  • Non-breaking change (add an optional field) usually needs no new version.
  • Breaking change (remove/rename a field, change types, change semantics) needs a version boundary.

This lesson compares the three classic strategies: URL path, Header, and Media-Type versioning.

Strategy 1: URL Path Versioning

The most common and most visible approach: put the version directly in the path, e.g. /v1/users and /v2/users.

  • Pros: obvious in logs and browsers, trivial to route, easy to cache, simple to document.
  • Cons: the version leaks into every URL; technically a URL should identify a resource, not a representation.

In FastAPI you express this with a prefix on an APIRouter. Each version gets its own router and its own prefix.

from fastapi import APIRouter, FastAPI

app = FastAPI()

v1 = APIRouter(prefix="/v1", tags=["v1"])
v2 = APIRouter(prefix="/v2", tags=["v2"])

@v1.get("/users/{user_id}")
def get_user_v1(user_id: int):
    return {"id": user_id, "name": "Ada Lovelace"}

@v2.get("/users/{user_id}")
def get_user_v2(user_id: int):
    # v2 splits name into first/last
    return {"id": user_id, "first_name": "Ada", "last_name": "Lovelace"}

app.include_router(v1)
app.include_router(v2)

Clean Route Grouping with Sub-Routers

Do not stack every endpoint onto one giant version router. Group by resource, then mount each resource router under the version router so structure stays clean as the API grows.

Here users_router is built independently and then included into v1. The combined path becomes /v1/users/....

from fastapi import APIRouter, FastAPI

app = FastAPI()

users_router = APIRouter(prefix="/users", tags=["users"])

@users_router.get("/{user_id}")
def get_user(user_id: int):
    return {"id": user_id, "name": "Grace Hopper"}

v1 = APIRouter(prefix="/v1")
v1.include_router(users_router)   # -> /v1/users/{user_id}

app.include_router(v1)

Strategy 2: Header Versioning

Here the URL stays clean (/users/42) and the client signals the version through a custom request header, commonly X-API-Version: 2.

  • Pros: URLs are version-free and stable; the resource path never changes.
  • Cons: harder to test in a browser, easy to forget the header, and caching layers must be told to vary on it.

In FastAPI you read the header with a typed parameter and branch (or dispatch) on it.

from fastapi import FastAPI, Header

app = FastAPI()

@app.get("/users/{user_id}")
def get_user(user_id: int, x_api_version: int = Header(default=1)):
    if x_api_version >= 2:
        return {"id": user_id, "first_name": "Ada", "last_name": "Lovelace"}
    return {"id": user_id, "name": "Ada Lovelace"}

A Dependency to Resolve the Version

Branching inside every endpoint gets messy. Extract the version logic into a reusable dependency that validates the header once and rejects unsupported versions with a clean 406.

Any endpoint can now depend on api_version and trust it is one of the supported values.

from fastapi import FastAPI, Header, HTTPException, Depends

app = FastAPI()
SUPPORTED = {1, 2}

def api_version(x_api_version: int = Header(default=1)) -> int:
    if x_api_version not in SUPPORTED:
        raise HTTPException(
            status_code=406,
            detail=f"Unsupported API version {x_api_version}",
        )
    return x_api_version

@app.get("/users/{user_id}")
def get_user(user_id: int, version: int = Depends(api_version)):
    return {"id": user_id, "version": version}

Strategy 3: Media-Type (Content Negotiation) Versioning

The most RESTful but least common approach. The client asks for a specific representation via the Accept header using a vendor media type:

  • Accept: application/vnd.myapp.v1+json
  • Accept: application/vnd.myapp.v2+json

The URL identifies the resource; the media type identifies the representation/version. This is true HTTP content negotiation.

  • Pros: URLs are clean and semantically pure; you version the representation, not the resource.
  • Cons: verbose, hard for casual clients, weak tooling support, easy to typo.

Parsing the Vendor Media Type

The core of media-type versioning is parsing the vendor string into a version number. That parsing is pure Python and easy to unit-test on its own, independent of any framework.

Below we extract the vN token from an Accept value, defaulting to v1 when it is missing or malformed.

import re

PATTERN = re.compile(r"application/vnd\.myapp\.v(\d+)\+json")

def parse_version(accept: str, default: int = 1) -> int:
    match = PATTERN.search(accept or "")
    return int(match.group(1)) if match else default

# A few quick checks
print(parse_version("application/vnd.myapp.v2+json"))  # 2
print(parse_version("application/json"))                # 1 (default)
print(parse_version("application/vnd.myapp.v10+json")) # 10

Wiring Media-Type Versioning into FastAPI

With the parser ready, plug it into a dependency that reads the Accept header. Endpoints stay clean and resource-focused while the version comes from content negotiation.

import re
from fastapi import FastAPI, Header, Depends

app = FastAPI()
PATTERN = re.compile(r"application/vnd\.myapp\.v(\d+)\+json")

def accept_version(accept: str = Header(default="")) -> int:
    m = PATTERN.search(accept)
    return int(m.group(1)) if m else 1

@app.get("/users/{user_id}")
def get_user(user_id: int, version: int = Depends(accept_version)):
    if version >= 2:
        return {"id": user_id, "first_name": "Ada", "last_name": "Lovelace"}
    return {"id": user_id, "name": "Ada Lovelace"}

Keeping Versions DRY with Transformers

Duplicating business logic per version rots fast. A cleaner pattern: compute the data once in a canonical internal shape, then run a small per-version transformer that adapts it to the contract each version promised.

This isolates contract differences in tiny, testable functions instead of forking your whole handler.

def canonical_user(user_id: int) -> dict:
    return {"id": user_id, "first": "Ada", "last": "Lovelace"}

def to_v1(u: dict) -> dict:
    return {"id": u["id"], "name": f"{u['first']} {u['last']}"}

def to_v2(u: dict) -> dict:
    return {"id": u["id"], "first_name": u["first"], "last_name": u["last"]}

VERSIONS = {1: to_v1, 2: to_v2}

def render(user_id: int, version: int) -> dict:
    return VERSIONS[version](canonical_user(user_id))

print(render(42, 1))  # {'id': 42, 'name': 'Ada Lovelace'}
print(render(42, 2))  # {'id': 42, 'first_name': 'Ada', 'last_name': 'Lovelace'}

Caching, Vary, and Documentation Pitfalls

Header and media-type versioning have a sharp edge: caches. If a proxy caches /users/42 without knowing about your version header, a v1 client may receive a cached v2 body.

  • Always send Vary: X-API-Version (or Vary: Accept for media-type versioning) so caches key on it.
  • URL versioning sidesteps this entirely because each version has a distinct URL.
  • Header/media-type versions are also harder to see in the auto-generated /docs schema, since the path looks identical across versions.

Choosing a Strategy and Deprecating Cleanly

Practical guidance for the bootcamp:

  • URL versioning is the default for public REST APIs: visible, cache-friendly, easy to onboard.
  • Header versioning suits internal services that want stable URLs and control both client and server.
  • Media-type versioning fits hypermedia/REST purists; rare in practice.

Whatever you pick, ship a deprecation plan: announce a sunset date, return a Deprecation/Sunset header on old versions, and keep them alive long enough for clients to migrate.

from fastapi import APIRouter
from fastapi.responses import JSONResponse

v1 = APIRouter(prefix="/v1")

@v1.get("/users/{user_id}")
def get_user_v1(user_id: int):
    body = {"id": user_id, "name": "Ada Lovelace"}
    headers = {
        "Deprecation": "true",
        "Sunset": "Wed, 31 Dec 2025 23:59:59 GMT",
        "Link": '</v2/users>; rel="successor-version"',
    }
    return JSONResponse(content=body, headers=headers)

Quick Check: Picking the Right Versioning Approach

Apply what you learned about the trade-offs between the three strategies.

Recap: Versioning Without Breakage

You compared three ways to version a FastAPI API:

  • URL path (/v1/users): visible, cache-friendly, easy to route via per-version APIRouter prefixes. The default for public APIs.
  • Header (X-API-Version): clean URLs, resolved with a dependency; remember Vary for caches.
  • Media-type (Accept: application/vnd.myapp.vN+json): purest REST, parsed from the Accept header; rare and verbose.

Keep routes grouped by resource and mounted under version routers, isolate contract differences in small per-version transformers, and always pair a new version with a clear deprecation/sunset plan so clients upgrade smoothly.

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

บทเรียน “การกำหนดเวอร์ชันด้วย URL ส่วนหัว และชนิดสื่อ” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การกำหนดเวอร์ชันด้วย URL ส่วนหัว และชนิดสื่อ” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส FastAPI Backend Development Bootcamp ให้อัปเกรดเป็น CoddyKit PRO คอร์ส FastAPI Backend Development Bootcamp มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การกำหนดเวอร์ชันด้วย URL ส่วนหัว และชนิดสื่อ”

เปรียบเทียบแนวทางการกำหนดเวอร์ชันและจัดกลุ่มเส้นทางให้เป็นระเบียบ เพื่อให้ไคลเอ็นต์อัปเกรดได้โดยไม่เสียหาย คุณปฏิบัติ FastAPI Backend Development Bootcamp ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน FastAPI Backend Development Bootcamp หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน FastAPI Backend Development Bootcamp บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน

บทเรียน “การกำหนดเวอร์ชันด้วย URL ส่วนหัว และชนิดสื่อ” ใช้เวลานานแค่ไหน

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

ฉันเขียนและรันโค้ดในบทเรียน FastAPI Backend Development Bootcamp นี้ได้ไหม

ได้ บทเรียน FastAPI Backend Development Bootcamp ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

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

  1. การกำหนดเวอร์ชันด้วย URL ส่วนหัว และชนิดสื่อ
  2. การแบ่งหน้าแบบเคอร์เซอร์เทียบกับออฟเซ็ตในระบบขนาดใหญ่
  3. พารามิเตอร์การกรองและการเรียงลำดับแบบไดนามิก
  4. การออกแบบซองหุ้มการตอบกลับที่เสถียร
← กลับไปที่ FastAPI Backend Development Bootcamp