受 TypeScript 啟發(fā),微軟又搞了一個神器!
TypeSpec 是什么
TypeSpec[1] 是一種高度可擴展的語言,可輕松描述 REST、OpenAPI、gRPC 和其他協(xié)議中常見的 API 結(jié)構(gòu)。TypeSpec 在生成多種不同的 API 描述格式、客戶端和服務端代碼、文檔等方面表現(xiàn)出色。有了 TypeSpec,你就可以擺脫那些拖慢你速度的手寫文件,并在幾秒鐘內(nèi)生成符合標準的 API Schemas。
TypeSpec 的特點
- 簡潔輕量:受 TypeScript 的啟發(fā),TypeSpec 是一種極簡語言,可幫助開發(fā)人員以熟悉的方式描述 API。
- 易集成:編寫 TypeSpec,發(fā)布為各種格式,快速與其它生態(tài)系統(tǒng)集成。
- 支持多種協(xié)議:TypeSpec 標準庫支持主流的 OpenAPI 3.0,JSON Schema 2020-12,Protobuf,和 JSON RPC 等協(xié)議。
- 功能強大:受益于龐大的 OpenAPI 工具生態(tài)系統(tǒng),可用于配置 API 網(wǎng)關(guān)、生成代碼和驗證數(shù)據(jù)。
- 保證數(shù)據(jù)一致性:定義要在 API 中使用的通用模型,使用 JSON Schema 發(fā)射器獲取類型的 JSON Schema,并使用它們驗證數(shù)據(jù)。
- 友好的開發(fā)體驗:在 VSCode 和 Visual Studio 編輯器中為了 TypeSpec 提供了全面的語言支持。比如,語法高亮、代碼補全等功能。
TypeSpec 使用示例
生成 OpenAPI 描述文件
圖片
生成 JSON Schema
圖片
生成 Protobuf
圖片
TypeSpec Playground
要快速體驗 TypeSpec 的功能,推薦你使用 TypeSpec 官方提供的 playground[2]。該 playground 預設了 API versioning、Discriminated unions、HTTP service、REST framework、Protobuf Kiosk 和 Json Schema 6 個不同的使用示例,并支持 File 和 Swagger UI 兩種視圖。
File 視圖
圖片
Swagger UI 視圖
圖片
TypeSpec 快速上手
1.安裝 @typespec/compiler 編譯器
npm install -g @typespec/compiler
2.安裝 VSCode 擴展
在 VSCode 中搜索 TypeSpec 安裝 TypeSpec for VS Code 擴展,或在瀏覽器中打開 TypeSpec for VS Code[3] 網(wǎng)址后點擊 Install 按鈕。
3.創(chuàng)建 TypeSpec 項目
首先新建一個新的目錄,然后在項目的根目錄下執(zhí)行以下命令:
tsp init
圖片
圖片
4.安裝項目依賴
tsp install
成功執(zhí)行上述命令后,在當前目錄下會生成以下目錄結(jié)構(gòu):
.
├── main.tsp
├── node_modules
├── package-lock.json
├── package.json
└── tspconfig.yaml
之后,打開 main.tsp 文件,輸入以下代碼:
import "@typespec/http";
using TypeSpec.Http;
@service({
title: "Widget Service",
})
namespace DemoService;
model Widget {
@visibility("read", "update")
@path
id: string;
weight: int32;
color: "red" | "blue";
}
@error
model Error {
code: int32;
message: string;
}
@route("/widgets")
@tag("Widgets")
interface Widgets {
@get list(): Widget[] | Error;
@get read(@path id: string): Widget | Error;
@post create(...Widget): Widget | Error;
@patch update(...Widget): Widget | Error;
@delete delete(@path id: string): void | Error;
@route("{id}/analyze") @post analyze(@path id: string): string | Error;
}
完成輸入后,運行 tsp compile . 命令執(zhí)行編譯操作。成功編譯后,在 tsp-output/@typespec/openapi3 目錄下就會生成 openapi.yaml 文件:
圖片
有關(guān) TypeSpec 的相關(guān)內(nèi)容就介紹到這里,如果你想進一步了解 TypeSpec 的基礎使用和高級用法,推薦你閱讀官方的使用文檔[4]。
參考資料
[1]TypeSpec: https://typespec.io/
[2]playground: https://typespec.io/playground
[3]TypeSpec for VS Code: https://marketplace.visualstudio.com/items?itemName=typespec.typespec-vscode
[4]使用文檔: https://typespec.io/docs