TypeSpec[1] 是一种高度可扩展的语言,可轻松描述 REST
、OpenAPI
、gRPC
和其他协议中常见的 API 结构。TypeSpec 在生成多种不同的 API 描述格式、客户端和服务端代码、文档等方面表现出色。有了 TypeSpec,你就可以摆脱那些拖慢你速度的手写文件,并在几秒钟内生成符合标准的 API Schemas。
要快速体验 TypeSpec 的功能,推荐你使用 TypeSpec 官方提供的 playground[2]。该 playground 预设了 API versioning
、Discriminated unions
、HTTP service
、REST framework
、Protobuf Kiosk
和 Json Schema
6 个不同的使用示例,并支持 File 和 Swagger UI 两种视图。
@typespec/compiler
编译器npm install -g @typespec/compiler
在 VSCode 中搜索 TypeSpec
安装 TypeSpec for VS Code 扩展,或在浏览器中打开 TypeSpec for VS Code[3] 网址后点击 Install 按钮。
首先新建一个新的目录,然后在项目的根目录下执行以下命令:
tsp init
tsp install
成功执行上述命令后,在当前目录下会生成以下目录结构:
.
├── 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 .
命令执行编译操作。成功编译后,在 tsp-output/@typespec/openapi3
目录下就会生成 openapi.yaml
文件:
有关 TypeSpec 的相关内容就介绍到这里,如果你想进一步了解 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
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有