typespec-api-operations

作者: github

RESTful CRUD 操作,適用於 TypeSpec API 外掛程式,包含路由、參數與適應性卡片。支援 GET、POST、PATCH 與 DELETE 操作,並提供路徑、查詢與主體參數,用於篩選、建立與更新。包含 GET 回應的適應性卡片視覺化,以及破壞性操作(POST、PATCH、DELETE)的確認對話框。提供完整的 CRUD 範例,包含模型、錯誤處理與多種查詢參數模式。內建測試提示與最佳實踐,適用於...

npx skills add https://github.com/github/awesome-copilot --skill typespec-api-operations

Add TypeSpec API Operations

Add RESTful operations to an existing TypeSpec API plugin for Microsoft 365 Copilot.

Adding GET Operations

Simple GET - List All Items

/**
 * List all items.
 */
@route("/items")
@get op listItems(): Item[];

GET with Query Parameter - Filter Results

/**
 * List items filtered by criteria.
 * @param userId Optional user ID to filter items
 */
@route("/items")
@get op listItems(@query userId?: integer): Item[];

GET with Path Parameter - Get Single Item

/**
 * Get a specific item by ID.
 * @param id The ID of the item to retrieve
 */
@route("/items/{id}")
@get op getItem(@path id: integer): Item;

GET with Adaptive Card

/**
 * List items with adaptive card visualization.
 */
@route("/items")
@card(#{
  dataPath: "$",
  title: "$.title",
  file: "item-card.json"
})
@get op listItems(): Item[];

Create the Adaptive Card (appPackage/item-card.json):

{
  "type": "AdaptiveCard",
  "$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
  "version": "1.5",
  "body": [
    {
      "type": "Container",
      "$data": "${$root}",
      "items": [
        {
          "type": "TextBlock",
          "text": "**${if(title, title, 'N/A')}**",
          "wrap": true
        },
        {
          "type": "TextBlock",
          "text": "${if(description, description, 'N/A')}",
          "wrap": true
        }
      ]
    }
  ],
  "actions": [
    {
      "type": "Action.OpenUrl",
      "title": "View Details",
      "url": "https://example.com/items/${id}"
    }
  ]
}

Adding POST Operations

Simple POST - Create Item

/**
 * Create a new item.
 * @param item The item to create
 */
@route("/items")
@post op createItem(@body item: CreateItemRequest): Item;

model CreateItemRequest {
  title: string;
  description?: string;
  userId: integer;
}

POST with Confirmation

/**
 * Create a new item with confirmation.
 */
@route("/items")
@post
@capabilities(#{
  confirmation: #{
    type: "AdaptiveCard",
    title: "Create Item",
    body: """
    Are you sure you want to create this item?
      * **Title**: {{ function.parameters.item.title }}
      * **User ID**: {{ function.parameters.item.userId }}
    """
  }
})
op createItem(@body item: CreateItemRequest): Item;

Adding PATCH Operations

Simple PATCH - Update Item

/**
 * Update an existing item.
 * @param id The ID of the item to update
 * @param item The updated item data
 */
@route("/items/{id}")
@patch op updateItem(
  @path id: integer,
  @body item: UpdateItemRequest
): Item;

model UpdateItemRequest {
  title?: string;
  description?: string;
  status?: "active" | "completed" | "archived";
}

PATCH with Confirmation

/**
 * Update an item with confirmation.
 */
@route("/items/{id}")
@patch
@capabilities(#{
  confirmation: #{
    type: "AdaptiveCard",
    title: "Update Item",
    body: """
    Updating item #{{ function.parameters.id }}:
      * **Title**: {{ function.parameters.item.title }}
      * **Status**: {{ function.parameters.item.status }}
    """
  }
})
op updateItem(
  @path id: integer,
  @body item: UpdateItemRequest
): Item;

Adding DELETE Operations

Simple DELETE

/**
 * Delete an item.
 * @param id The ID of the item to delete
 */
@route("/items/{id}")
@delete op deleteItem(@path id: integer): void;

DELETE with Confirmation

/**
 * Delete an item with confirmation.
 */
@route("/items/{id}")
@delete
@capabilities(#{
  confirmation: #{
    type: "AdaptiveCard",
    title: "Delete Item",
    body: """
    ⚠️ Are you sure you want to delete item #{{ function.parameters.id }}?
    This action cannot be undone.
    """
  }
})
op deleteItem(@path id: integer): void;

Complete CRUD Example

Define the Service and Models

@service
@server("https://api.example.com")
@actions(#{
  nameForHuman: "Items API",
  descriptionForHuman: "Manage items",
  descriptionForModel: "Read, create, update, and delete items"
})
namespace ItemsAPI {
  
  // Models
  model Item {
    @visibility(Lifecycle.Read)
    id: integer;
    
    userId: integer;
    title: string;
    description?: string;
    status: "active" | "completed" | "archived";
    
    @format("date-time")
    createdAt: utcDateTime;
    
    @format("date-time")
    updatedAt?: utcDateTime;
  }

  model CreateItemRequest {
    userId: integer;
    title: string;
    description?: string;
  }

  model UpdateItemRequest {
    title?: string;
    description?: string;
    status?: "active" | "completed" | "archived";
  }

  // Operations
  @route("/items")
  @card(#{ dataPath: "$", title: "$.title", file: "item-card.json" })
  @get op listItems(@query userId?: integer): Item[];

  @route("/items/{id}")
  @card(#{ dataPath: "$", title: "$.title", file: "item-card.json" })
  @get op getItem(@path id: integer): Item;

  @route("/items")
  @post
  @capabilities(#{
    confirmation: #{
      type: "AdaptiveCard",
      title: "Create Item",
      body: "Creating: **{{ function.parameters.item.title }}**"
    }
  })
  op createItem(@body item: CreateItemRequest): Item;

  @route("/items/{id}")
  @patch
  @capabilities(#{
    confirmation: #{
      type: "AdaptiveCard",
      title: "Update Item",
      body: "Updating item #{{ function.parameters.id }}"
    }
  })
  op updateItem(@path id: integer, @body item: UpdateItemRequest): Item;

  @route("/items/{id}")
  @delete
  @capabilities(#{
    confirmation: #{
      type: "AdaptiveCard",
      title: "Delete Item",
      body: "⚠️ Delete item #{{ function.parameters.id }}?"
    }
  })
  op deleteItem(@path id: integer): void;
}

Advanced Features

Multiple Query Parameters

@route("/items")
@get op listItems(
  @query userId?: integer,
  @query status?: "active" | "completed" | "archived",
  @query limit?: integer,
  @query offset?: integer
): ItemList;

model ItemList {
  items: Item[];
  total: integer;
  hasMore: boolean;
}

Header Parameters

@route("/items")
@get op listItems(
  @header("X-API-Version") apiVersion?: string,
  @query userId?: integer
): Item[];

Custom Response Models

@route("/items/{id}")
@delete op deleteItem(@path id: integer): DeleteResponse;

model DeleteResponse {
  success: boolean;
  message: string;
  deletedId: integer;
}

Error Responses

model ErrorResponse {
  error: {
    code: string;
    message: string;
    details?: string[];
  };
}

@route("/items/{id}")
@get op getItem(@path id: integer): Item | ErrorResponse;

Testing Prompts

After adding operations, test with these prompts:

GET Operations:

  • "List all items and show them in a table"
  • "Show me items for user ID 1"
  • "Get the details of item 42"

POST Operations:

  • "Create a new item with title 'My Task' for user 1"
  • "Add an item: title 'New Feature', description 'Add login'"

PATCH Operations:

  • "Update item 10 with title 'Updated Title'"
  • "Change the status of item 5 to completed"

DELETE Operations:

  • "Delete item 99"
  • "Remove the item with ID 15"

Best Practices

Parameter Naming

  • Use descriptive parameter names: userId not uid
  • Be consistent across operations
  • Use optional parameters (?) for filters

Documentation

  • Add JSDoc comments to all operations
  • Describe what each parameter does
  • Document expected responses

Models

  • Use @visibility(Lifecycle.Read) for read-only fields like id
  • Use @format("date-time") for date fields
  • Use union types for enums: "active" | "completed"
  • Make optional fields explicit with ?

Confirmations

  • Always add confirmations to destructive operations (DELETE, PATCH)
  • Show key details in confirmation body
  • Use warning emoji (⚠️) for irreversible actions

Adaptive Cards

  • Keep cards simple and focused
  • Use conditional rendering with ${if(..., ..., 'N/A')}
  • Include action buttons for common next steps
  • Test data binding with actual API responses

Routing

  • Use RESTful conventions:
    • GET /items - List
    • GET /items/{id} - Get one
    • POST /items - Create
    • PATCH /items/{id} - Update
    • DELETE /items/{id} - Delete
  • Group related operations in the same namespace
  • Use nested routes for hierarchical resources

Common Issues

Issue: Parameter not showing in Copilot

Solution: Check parameter is properly decorated with @query, @path, or @body

Issue: Adaptive card not rendering

Solution: Verify file path in @card decorator and check JSON syntax

Issue: Confirmation not appearing

Solution: Ensure @capabilities decorator is properly formatted with confirmation object

Issue: Model property not appearing in response

Solution: Check if property needs @visibility(Lifecycle.Read) or remove it if it should be writable

來自 github 的更多技能

console-rendering
github
在 Go 中使用基於結構體標籤的控制台渲染系統的說明
official
acquire-codebase-knowledge
github
當使用者明確要求對現有程式碼庫進行映射、文件化或入門引導時,使用此技能。觸發詞如「映射此程式碼庫」、「文件化…」等提示。
official
acreadiness-assess
github
Run the AgentRC readiness assessment on the current repository and produce a static HTML dashboard at reports/index.html. Wraps `npx github:microsoft/agentrc…
official
acreadiness-generate-instructions
github
透過 AgentRC 指令命令生成量身打造的 AI 代理指令檔案。產生 .github/copilot-instructions.md(預設,建議用於 VS Code 中的 Copilot…
official
acreadiness-policy
github
幫助使用者選取、撰寫或套用 AgentRC 政策。政策可透過停用不相關的檢查、覆寫影響/等級、設定…來自訂整備度評分。
official
add-educational-comments
github
為程式碼檔案添加教育性註解,將其轉化為有效的學習資源。根據三個可設定的知識層級(初學者、中級、進階)調整解釋深度與語氣。若未提供檔案,會自動請求提供,並以編號清單對應以便快速選取。僅透過教育性註解將檔案擴充最多125%(嚴格上限:400行新註解;超過1,000行的檔案上限為300行)。保留檔案編碼、縮排風格、語法正確性及……
official
adobe-illustrator-scripting
github
使用 ExtendScript (JavaScript/JSX) 編寫、除錯及最佳化 Adobe Illustrator 自動化腳本。適用於建立或修改操控…的腳本時。
official
agent-governance
github
宣告式政策、意圖分類與稽核軌跡,用於控制AI代理工具存取與行為。可組合的治理政策定義允許/封鎖的工具、內容過濾器、速率限制與核准要求——以配置而非程式碼形式儲存。語意意圖分類在工具執行前,透過基於模式的訊號偵測危險提示(資料外洩、權限提升、提示注入)。工具層級治理裝飾器在函式層級強制執行政策……
official