Logo Endpoint

Endpoint

Cộng đồng
ewtryocb
endpoint

Use when creating or editing a FastAPI endpoint under src/presentation/http/v1/endpoints/<audience>/. Enforces audience-first organization (public/user/admin/internal), the exact parameter-naming convention (data for bodies, query for GET filters), the five-parameter list shape, correct Require + Authorization wiring, and strict contract ↔ Result mapping.

Tổng quan

Nhà phát hànhewtryocb
Kho mãfastapi-claude-template
Tên kỹ năngendpoint
Sao
33
Bản fork
5
Tệp đi kèm
Chỉ có hướng dẫn
Giấy phépMIT
Liên kết
  • Hướng dẫn bằng Markdown

    Tệp SKILL.md được mô hình tải khi cần, nên chỉ tốn token khi có yêu cầu thực sự phù hợp.

  • Dùng được với mọi LLM

    Kỹ năng AI là Markdown thuần túy, không phải mã dành riêng cho một nhà cung cấp, nên dùng được với GPT, Claude, Gemini, Grok hoặc mô hình cục bộ.

  • Đầy đủ trong hướng dẫn

    Mọi thứ mô hình cần đều nằm trong hướng dẫn — không có tệp bổ sung cần đồng bộ.

  • Mã nguồn mở

    Được ewtryocb công bố trên GitHub. Hãy đọc nội dung nguồn trước khi cài đặt.

Cài đặt

Cài đặt kỹ năng AI Endpoint trong TypingMind để dùng với bất kỳ LLM nào, hoặc thêm vào một tác nhân AI khác có thể đọc SKILL.md.

1

Cài đặt trong TypingMind

TypingMind cài đặt kỹ năng trực tiếp từ thư mục GitHub — đọc SKILL.md, đóng gói các tệp tài nguyên và lưu kết quả trên máy.

  1. Mở ứng dụng và vào Plugin → Kỹ năng.
  2. Chọn "Cài đặt từ GitHub".
  3. Dán URL thư mục kỹ năng bên dưới và xác nhận.
    https://github.com/ewtryocb/fastapi-claude-template/tree/master/.claude/skills/endpoint
  4. Bật kỹ năng trong từng cuộc trò chuyện mà bạn muốn sử dụng kỹ năng đó.
Plugin → Kỹ năng → Thêm kỹ năng → Từ URL GitHub, sau đó dán URL thư mục và nhấn Tiếp tục.
2

Cài đặt trong tác nhân AI khác

Bất kỳ tác nhân AI nào đọc được định dạng Agent Skills đều có thể dùng kỹ năng này — hãy sao chép thư mục vào thư mục kỹ năng của tác nhân AI đó.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/ewtryocb/fastapi-claude-template.git /tmp/fastapi-claude-template
mkdir -p .claude/skills
cp -r /tmp/fastapi-claude-template/.claude/skills/endpoint .claude/skills/endpoint
Khởi động lại Claude Code sau khi sao chép để ứng dụng nhận kỹ năng mới.

Sử dụng trong TypingMind

Bật Endpoint trong bất kỳ cuộc trò chuyện nào trên TypingMind, mô hình sẽ tự xử lý phần còn lại. Tên và mô tả của kỹ năng nằm trong prompt hệ thống. Ngay khi có yêu cầu phù hợp, mô hình tự tải toàn bộ hướng dẫn — bạn không cần gọi thủ công và kỹ năng không tốn token cho đến khi thực sự được dùng.

Mô hình tự tải Endpoint ngay khi có yêu cầu phù hợp.

Dùng được với mọi mô hình AI

Kỹ năng AI là các hướng dẫn Markdown thuần túy, không phải mã dành riêng cho một nhà cung cấp, nên Endpoint không bị giới hạn ở mô hình mà kỹ năng này được viết cho. Chỉ cần cài đặt một lần trong TypingMind rồi dùng với GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama hoặc mô hình cục bộ do bạn tự chạy — tất cả đều dùng khóa API của riêng bạn.

  • Chỉ tải khi cần

    Prompt hệ thống chỉ chứa tên và mô tả. Hướng dẫn được tải khi có yêu cầu phù hợp đầu tiên, nên kỹ năng chưa dùng không tốn chi phí.

  • Đổi mô hình ngay trong cuộc trò chuyện

    Vì kỹ năng là hướng dẫn chứ không phải mã, việc đổi mô hình không làm kỹ năng ngừng hoạt động — mô hình tiếp theo vẫn đọc cùng tệp SKILL.md.

Hướng dẫn của kỹ năng

Đây là nội dung SKILL.md mà mô hình tải. Hãy đọc trước khi cài đặt — kỹ năng là những hướng dẫn mà mô hình của bạn sẽ làm theo.

Writing HTTP endpoints (src/presentation/http/v1/endpoints/<audience>/)

Endpoints are thin adapters. They have no business logic, no DB access, no validation beyond schema parsing. Their job is contract → Request → request_bus.send() → OkResponse(contract.from(result)).

Pick the audience folder first

Endpoints live under presentation/http/v1/endpoints/<audience>/ where <audience> decides auth:

FolderRouter guardUse for
public/nonehealthcheck, register, login, refresh, public forms
user/Authorization() (any authenticated user)/users/me, logout, anything user-owned
admin/Authorization("Admin")admin user management, moderation, cross-user operations
internal/service-to-service stub, include_in_schema=Falsewebhooks, internal APIs

You never attach Authorization(...) at the endpoint function level when the router already enforces it. FastAPI caches the dependency result per request, so declaring user: Annotated[UserResult, Require(Authorization())] as a parameter inside a user/-audience endpoint is free — it returns the same cached UserResult that the router-level guard already validated.

Endpoint file skeleton

python
# src/presentation/http/v1/endpoints/admin/widget.py
from typing import Annotated

import uuid_utils.compat as uuid
from dishka.integrations.fastapi import DishkaRoute
from fastapi import APIRouter, Query, status
from fastapi import Depends as Require

from src.application.common.interfaces.request_bus import RequestBus
from src.application.common.pagination import OffsetPagination
from src.application.v1.results import OffsetResult, WidgetResult
from src.application.v1.usecases.widget import (
    CreateWidgetRequest,
    SelectManyWidgetRequest,
    SelectWidgetRequest,
    UpdateWidgetRequest,
)
from src.common.di import Depends
from src.database.psql.types.widget import WidgetLoads
from src.presentation.http.common.responses import OkResponse
from src.presentation.http.v1 import contracts

admin_widget_router = APIRouter(
    prefix="/widgets", tags=["Admin | Widget"], route_class=DishkaRoute
)

Fixed imports

  • from fastapi import Depends as Require — the project always aliases Depends → Require to make the intent obvious.
  • from src.common.di import Depends — this is Dishka's Depends[T] marker used for DI, different from FastAPI's Depends. Use Depends[RequestBus] etc. as parameter annotations.
  • from dishka.integrations.fastapi import DishkaRoute — every APIRouter passes route_class=DishkaRoute so Dishka can inject into endpoints.
  • tags=["<Audience> | <Resource>"] — two-word tag with a pipe, e.g. "Admin | User", "Admin | Widget", "User", "Public".

Result → Contract mapping

Endpoints always hand the client a Contract, never a raw Result. There are two shapes:

  • Single item: contracts.User.model_validate(result) — pass the Result instance directly. No .model_dump() round-trip needed; Contract inherits from_attributes=True, so Pydantic reads attributes off the Result object in place.
  • Paginated list: result.map(contracts.User.model_validate) — OffsetResult.map(fn) applies fn to every item in .data and returns a new OffsetResult[R] with the same offset/limit/total. No manual unpacking, no re-building the envelope.

The OffsetResult[T] envelope is layer-agnostic — defined once in application/v1/results/base.py and reused as both the use case return type and the HTTP response type. You use the application class for response_model=OffsetResult[contracts.User]. There is no contracts.OffsetResult.

Parameter naming — non-negotiable

HTTP methodInput sourceParameter nameType annotation
GETquery string filtersqueryAnnotated[contracts.SelectWidgets, Require(contracts.SelectWidgets)]
POST/PATCH/PUT/DELETEJSON bodydatacontracts.CreateWidget (direct, FastAPI parses body automatically)
pathpath paramswidget_uuid: uuid.UUID (literal FastAPI path)—
extras for GETstandalone primitivesnamed (loads, order_by)tuple[WidgetLoads, ...] = Query(default=(), title="...")

Never use body, payload, params, queries, input, args. The project is consistent — query for GET filters, data for mutation bodies.

The five-parameter list shape (GET /widgets)

Every list endpoint uses exactly this shape — do not deviate, do not reorder:

python
@admin_widget_router.get(
    "",
    response_model=OffsetResult[contracts.Widget],
    status_code=status.HTTP_200_OK,
)
async def select_widgets_endpoint(
    request_bus: Depends[RequestBus],
    query: Annotated[contracts.SelectWidgets, Require(contracts.SelectWidgets)],
    pagination: Annotated[
        contracts.OffsetPagination, Require(contracts.OffsetPagination)
    ],
    loads: tuple[WidgetLoads, ...] = Query(
        default=(), title="Additional relations"
    ),
) -> OkResponse[OffsetResult[contracts.Widget]]:
    result: OffsetResult[WidgetResult] = await request_bus.send(
        SelectManyWidgetRequest(
            loads=loads,
            **query.model_dump(),
            pagination=OffsetPagination(**pagination.model_dump()),
        )
    )
    return OkResponse(result.map(contracts.Widget.model_validate))

Five things to notice:

  1. query: Annotated[ContractCls, Require(ContractCls)] — Require(ContractCls) tells FastAPI to treat the Pydantic model's fields as separate query string parameters. This works for flat primitives (str | None, UUID | None, int, Literal[...]). Nested/complex types break — keep filter contracts flat.
  2. pagination: Annotated[contracts.OffsetPagination, Require(contracts.OffsetPagination)] — same trick for pagination params. contracts.OffsetPagination is the strict version (10 ≤ limit ≤ 200, offset ≥ 0). It is mapped to the lenient application version on the request_bus.send line: OffsetPagination(**pagination.model_dump()). In the endpoint module the unqualified OffsetPagination refers to the application class (imported from src.application.common.pagination), and contracts.OffsetPagination refers to the strict HTTP contract class — no name collision.
  3. loads: tuple[WidgetLoads, ...] = Query(default=(), title="...") — a separate standalone query parameter, not nested inside the filter contract. Lets the frontend opt in to relations per request. Forward as-is to the Request.
  4. await request_bus.send(SelectManyWidgetRequest(loads=loads, **query.model_dump(), pagination=OffsetPagination(**pagination.model_dump()))) — flat kwargs from the query contract, pagination mapped, loads forwarded.
  5. result.map(contracts.Widget.model_validate) — the generic envelope .map() retargets the item type without re-building offset/limit/total manually. contracts.Widget.model_validate(widget_result) works because Contract uses from_attributes=True.

Single GET / PATCH / POST shapes

GET one (path param)

python
@admin_widget_router.get(
    "/{widget_uuid}",
    response_model=contracts.Widget,
    status_code=status.HTTP_200_OK,
)
async def select_widget_endpoint(
    widget_uuid: uuid.UUID,
    request_bus: Depends[RequestBus],
    loads: tuple[WidgetLoads, ...] = Query(
        default=(), title="Additional relations"
    ),
) -> OkResponse[contracts.Widget]:
    result: WidgetResult = await request_bus.send(
        SelectWidgetRequest(widget_uuid=widget_uuid, loads=loads)
    )
    return OkResponse(contracts.Widget.model_validate(result))

POST body

python
@admin_widget_router.post(
    "",
    response_model=contracts.Widget,
    status_code=status.HTTP_201_CREATED,
)
async def create_widget_endpoint(
    data: contracts.CreateWidget,
    request_bus: Depends[RequestBus],
) -> OkResponse[contracts.Widget]:
    result: WidgetResult = await request_bus.send(
        CreateWidgetRequest(**data.model_dump())
    )
    return OkResponse(contracts.Widget.model_validate(result))

PATCH with path + body

python
@admin_widget_router.patch(
    "/{widget_uuid}",
    response_model=contracts.Widget,
    status_code=status.HTTP_200_OK,
)
async def update_widget_endpoint(
    widget_uuid: uuid.UUID,
    data: contracts.AdminUpdateWidget,
    request_bus: Depends[RequestBus],
) -> OkResponse[contracts.Widget]:
    result: WidgetResult = await request_bus.send(
        UpdateWidgetRequest(
            widget_uuid=widget_uuid,
            **data.model_dump(exclude_unset=True),
        )
    )
    return OkResponse(contracts.Widget.model_validate(result))

Note exclude_unset=True — PATCH bodies should forward only the fields the client actually sent, so the use case can distinguish "not provided" from "set to null".

User-scoped endpoint (/me) — identity comes from the guard, never the client

When the endpoint lives under user/ audience and operates on the caller's own data, the target identifier must come from the authenticated user parameter, never from the path or body:

python
@user_me_router.patch(
    "",
    response_model=contracts.User,
    status_code=status.HTTP_200_OK,
)
async def update_self_endpoint(
    data: contracts.UpdateSelf,                              # ← NO role_uuid, NO active, NO user_uuid
    request_bus: Depends[RequestBus],
    user: Annotated[UserResult, Require(Authorization())],   # ← identity from JWT
) -> OkResponse[contracts.User]:
    result: UserResult = await request_bus.send(
        UpdateUserRequest(
            user_uuid=user.uuid,                              # ← from guard, never from client
            **data.model_dump(exclude_unset=True),
        )
    )
    return OkResponse(contracts.User.model_validate(result))

This is a hard rule — the architecture reviewer will fail any user endpoint that accepts an identifier in the path/body when the guard already provides it.

Contract rules — the split between user and admin

For every mutation with a user-facing version and an admin-facing version, you need two separate contracts:

python
# presentation/http/v1/contracts/widget.py

class UpdateSelfWidget(Contract):
    """Fields a user may change about their own widget."""
    name: str | None = None

class AdminUpdateWidget(Contract):
    """Fields an admin may change about any widget."""
    name: str | None = None
    owner_uuid: uuid.UUID | None = None    # privileged: reassign ownership
    active: bool | None = None              # privileged: moderation

Privileged fields that must NEVER appear in a user contract:

  • role_uuid, role, is_admin, permissions, scopes
  • active, banned, email_verified
  • user_uuid, target_uuid, id (identity is from the guard, not the payload)
  • login, email (identity fields)
  • quota, tier, plan (billing-controlled)

Fields that must NEVER appear in a response contract (any audience):

  • password, password_hash, hashed_password, salt
  • refresh_token, access_token (unless you're returning a freshly issued pair in login/refresh)
  • secret, api_key, private_key
  • stripe_customer_id, internal_note
  • Any column from a DB model that you'd be uncomfortable seeing in a server log

If the Result type includes such a field, that's fine (application layer can have rich data) — but the Contract is the filter. List only the fields the client is allowed to see.

Router wiring (the __init__.py)

Each audience folder has a __init__.py that composes its endpoint files into a router with audience-level auth:

python
# src/presentation/http/v1/endpoints/admin/__init__.py
from fastapi import APIRouter
from fastapi import Depends as Require

from src.presentation.http.v1.guards import Authorization

from .user import admin_user_router
from .widget import admin_widget_router


def setup_admin_router() -> APIRouter:
    router = APIRouter(
        prefix="/admin",
        dependencies=[Require(Authorization("Admin"))],
    )
    router.include_router(admin_user_router)
    router.include_router(admin_widget_router)
    return router

Then register the setup function in src/presentation/http/v1/endpoints/__init__.py::setup_v1_routers().

Anti-patterns (hard no)

  • ❌ Business logic inside an endpoint (if user.role.name == "Admin": ..., DB calls, conditional mediation). Push it into a use case.
  • ❌ Using body, payload, params, queries as parameter names. It's data for bodies, query for GET filters.
  • ❌ Authorization("Admin") inside an endpoint parameter when the router already declares it. It double-validates the JWT.
  • ❌ Authorization() (no role) in an admin/ endpoint when the user must be Admin. The router should enforce "Admin".
  • ❌ Declaring a path parameter like /users/{user_uuid} under user/ audience — users shouldn't target themselves via path, use /users/me or /me.
  • ❌ Accepting role_uuid, active, is_admin in an UpdateSelf* contract.
  • ❌ Returning a raw Result from the use case — always wrap in OkResponse(contracts.X.model_validate(result)) (the intermediate .model_dump() is unnecessary because Contract sets from_attributes=True), or use result.map(contracts.X.model_validate) for OffsetResult.
  • ❌ Forgetting route_class=DishkaRoute on APIRouter(...). Without it, Dishka can't inject into endpoint parameters.
  • ❌ Hard-coding limit=10 or any pagination behavior in the endpoint — pagination lives in contracts.OffsetPagination.
  • ❌ Calling the contract's OffsetPagination as pagination: OffsetPagination = OffsetPagination() — that's the application version. The endpoint must use contracts.OffsetPagination via Require.

Câu hỏi thường gặp

Kỹ năng AI Endpoint làm được gì?

Use when creating or editing a FastAPI endpoint under src/presentation/http/v1/endpoints/<audience>/. Enforces audience-first organization (public/user/admin/internal), the exact parameter-naming convention (data for bodies, query for GET filters), the five-parameter list shape, correct Require + Authorization wiring, and strict contract ↔ Result mapping.

Vì sao nên dùng Endpoint trên TypingMind?

Vì bạn chỉ cần cài một lần rồi dùng với bất kỳ mô hình nào. Endpoint là nội dung Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên cùng một kỹ năng có thể chạy trên GPT-5, Claude, Gemini, Grok hoặc mô hình trên thiết bị — và bạn có thể đổi mô hình ngay trong cuộc trò chuyện mà kỹ năng vẫn hoạt động. TypingMind dùng khóa API riêng của bạn, nên bạn thanh toán trực tiếp cho nhà cung cấp thay vì trả phí thuê bao theo suất người dùng, đồng thời kỹ năng và các cuộc trò chuyện vẫn nằm trong bộ lưu trữ của bạn.

Làm thế nào để cài Endpoint trong TypingMind?

Mở Plugin → Kỹ năng → Cài đặt từ GitHub trong TypingMind rồi dán https://github.com/ewtryocb/fastapi-claude-template/tree/master/.claude/skills/endpoint. TypingMind đọc tệp SKILL.md và cài đặt thành một kỹ năng mà bạn có thể bật cho từng cuộc trò chuyện.

Những mô hình AI nào có thể dùng Endpoint?

Bất kỳ mô hình nào bạn kết nối trong TypingMind. Kỹ năng AI là các hướng dẫn bằng Markdown chứ không phải mã dành riêng cho từng nhà cung cấp, nên GPT, Claude, Gemini, Grok và các mô hình chạy trên thiết bị đều có thể tải kỹ năng này khi có yêu cầu phù hợp.

Bạn có thể dùng Endpoint với bao nhiêu mô hình AI?

Bao nhiêu cũng được. Miễn là mô hình hỗ trợ kỹ năng, bạn có thể dùng Endpoint với mô hình đó — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama và nhiều mô hình khác — tất cả đều trên TypingMind với khóa API riêng của bạn.

Kỹ năng AI Endpoint có miễn phí không?

Có. Kỹ năng này được ewtryocb phát hành trên GitHub theo giấy phép MIT. Bạn chỉ trả tiền cho nhà cung cấp AI của mình theo số token đã dùng.

Kỹ năng AI là gì?

Kỹ năng AI là một gói hướng dẫn có thể tái sử dụng, chỉ cho mô hình AI cách thực hiện một tác vụ cụ thể. Kỹ năng tuân theo định dạng mở Agent Skills: một tệp SKILL.md chứa tên và mô tả, cùng các tập lệnh, mẫu hoặc tệp tham khảo mà mô hình có thể cần. Mô hình chỉ đọc hướng dẫn khi yêu cầu của bạn phù hợp với kỹ năng, nên kỹ năng đã cài đặt không phát sinh chi phí cho đến khi được sử dụng.

Kỹ năng AI khác gì với plugin hoặc máy chủ MCP?

Plugin hoặc máy chủ MCP cung cấp cho mô hình các công cụ mới để gọi — mã được chạy ở đâu đó và trả về kết quả. Còn kỹ năng AI cung cấp kiến thức và quy trình: cách tiếp cận tác vụ, các bước cần thực hiện và tiêu chí của đầu ra tốt. Kỹ năng chỉ là nội dung Markdown, nên không cần máy chủ, khóa API hay môi trường thực thi và hoạt động với mọi mô hình.

Xem tất cả

Tạo ngay không gian làm việc AI riêng

Đăng ký bản tin của chúng tôi để nhận thông báo về tính năng mới và các đợt tặng quà sắp tới 👇