An Introduction to TypeSpec: Features, Usage Examples, and Quick Start Guide
This article introduces TypeSpec, a lightweight, extensible language for describing REST, OpenAPI, gRPC and other APIs, outlines its key features, demonstrates how to generate OpenAPI, JSON Schema and Protobuf files, and provides step‑by‑step instructions for installing the compiler, setting up the VS Code extension, creating a project, and compiling a sample service.
What is TypeSpec
TypeSpec is a highly extensible language for describing REST, OpenAPI, gRPC and other API structures. It enables generation of multiple API description formats, client/server code, documentation, etc., allowing developers to avoid hand‑written files and generate standard API schemas in seconds.
Features of TypeSpec
Concise and lightweight, inspired by TypeScript.
Easy integration with various ecosystems.
Supports multiple protocols: OpenAPI 3.0, JSON Schema 2020‑12, Protobuf, JSON RPC.
Powerful capabilities via the extensive OpenAPI tool ecosystem.
Ensures data consistency with shared models and JSON Schema validation.
Friendly developer experience with VS Code and Visual Studio language support.
Usage Examples
Generate OpenAPI description file
Generate JSON Schema
Generate Protobuf
TypeSpec Playground
The official playground provides six usage examples (API versioning, discriminated unions, HTTP service, REST framework, Protobuf Kiosk, Json Schema) and supports File and Swagger UI views.
Quick Start
1. Install the compiler
npm install -g @typespec/compiler2. Install VS Code extension
Search for “TypeSpec” in VS Code and install the “TypeSpec for VS Code” extension, or click the Install button on the marketplace page.
3. Create a TypeSpec project
tsp init4. Install project dependencies
tsp installAfter installation, the directory structure includes main.tsp, node_modules, package.json, etc.
5. Write a service definition
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;
}Compile with tsp compile . to generate OpenAPI YAML in tsp-output/@typespec/openapi3/openapi.yaml .
For more details, refer to the official documentation.
IT Services Circle
Delivering cutting-edge internet insights and practical learning resources. We're a passionate and principled IT media platform.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.