iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
😤

Introducing TypeSpec: A Great Way to Author OpenAPI and JSON Schemas

に公開

Introducing TypeSpec: Why It’s Great for Writing OpenAPI and JSON Schema

I would like to introduce TypeSpec, which allows you to define OpenAPI and JSON Schemas—often redundant and tedious to write—with a great, type-safe developer experience.

Background

I wanted to use the SwitchBot API and checked if an OpenAPI schema was available. However, the SwitchBot API documentation is written in Markdown, so unfortunately, I couldn't generate client code directly from OpenAPI.

So, I considered creating an OpenAPI schema from the documentation myself. Writing an OpenAPI Schema from scratch is quite a chore, but when I tried using TypeSpec, I found it very user-friendly. I'd like to share my experience.

What is TypeSpec?

TypeSpec is a language for defining API schemas and more, developed by Microsoft. Looking at the official description:

TypeSpec is a language for defining cloud service APIs and their shapes. TypeSpec is a highly extensible language with primitives that can describe API shapes common to REST, OpenAPI, gRPC, and other protocols. (Translated via DeepL)

While the main focus of this article is writing OpenAPI, it can also be used to define schemas for JSON Schema, gRPC, and others.

The writing experience is very similar to TypeScript. In short, it feels like a tool that lets you "write schema definitions in TypeScript and transpiles them into OAS (OpenAPI Specification)."

Just as TypeScript is transpiled into JavaScript, the schema information written in TypeSpec is exported as an OpenAPI schema.

What are the Benefits?

First of all, as a premise, OpenAPI is highly expressive as a method for defining API schemas and can describe schemas quite accurately.

It provides abstraction at the object level using components, and although redundant, it is also possible to express union types using oneOf and anyOf, and intersection types (or inheritance) using allOf.

However, while the expressiveness is sufficient, the notation is quite redundant, making it very difficult for humans to write by hand.

For example:

// TypeScript code
type NormalUser = {
  id: string
  name: string
}

type SuperUser = NormalUser & {
  role: "owner" | "manager"
}

type User = NormalUser | SuperUser // I want to use this as a response type!

If you want to express something like this and try to describe it in OpenAPI (JSON Schema):

components:
  schemas:
    NormalUser:
      type: object
      properties:
        id:
          type: string
        name:
          type: string
      required:
        - id
        - name
    SuperUser:
      type: object
      properties:
        role:
          type: string
          enum:
            - owner
            - manager
      allOf:
        - $ref: "#/components/schemas/NormalUser"
    User:
      oneOf:
        - $ref: "#/components/schemas/NormalUser"
        - $ref: "#/components/schemas/SuperUser"

It ends up looking like the above.

In addition to the relative difficulty of expressing the types a developer has in mind, there are pain points such as numerous boilerplate descriptions and the inability to split files, which makes it hard to notice issues.

In that regard, by using TypeSpec, it takes care of these hassles, allowing developers to focus on what they originally wanted to do: "describing the API specifications."

In fact, the TypeSpec code to represent this model is almost identical to the TypeScript code:

model NormalUser {
  name: string;
  age: numeric;
}

model SuperUser extends NormalUser {
  role: "manager" | "owner";
}

alias User = NormalUser | SuperUser;

That's it—and you can see that it's much more intuitive than writing JSON Schema directly.

Let's Look at the Usage

In this article, I won't touch upon environment setup for TypeSpec; I'll limit the discussion to how you can write it. Please refer to the Official Documentation's Getting Started and the repository where I wrote the OpenAPI Spec for the SwitchBot API this time.

One of the great things about TypeSpec is that the VSCode extension is well-built, so I highly recommend installing and using it.

As expected from Microsoft, the creators of TypeScript and Pylance, it works very solidly at a practical level, which was impressive.

It's quite easy to write because you get accurate completions using types, and the editor flags issues that can be detected through static analysis.

Here is the repository I used this time:

https://github.com/d-kimuson/switchbot-api-openapi

(As a side note) If you want to use the SwitchBot API but are having trouble because there is no OpenAPI Spec, feel free to use this.

Looking at the Syntax

model

As mentioned briefly at the beginning, you use model to define data structures.

model NormalUser {
  name: string;
  age: numeric;
}

Models can be inherited, and you can write it like this:

model SuperUser extends NormalUser {
  role: "manager" | "owner";
}

Literal types and their unions can also be written like TypeScript, which is very convenient.

Things defined with model are exported to components in the OpenAPI specification, and extends is represented using allOf.

components:
  schemas:
    NormalUser:
      type: object
      required:
        - name
        - age
      properties:
        name:
          type: string
        age:
          type: number
    SuperUser:
      type: object
      required:
        - role
      properties:
        role:
          type: string
          enum:
            - manager
            - owner
      allOf:
        - $ref: "#/components/schemas/NormalUser"

Type Aliases

While model cannot represent a concept equivalent to "OR," descriptions like modelA or modelB can be achieved using alias.
alias provides a similar user experience to TypeScript's type aliases (type).

alias SampleObject = {
  name: string
};
alias User = NormalUser | SuperUser;

Looking at this alone, it might seem like alias is a superior version of model and that you could just use alias for everything. However, the conclusion is that it is better to use model for actual data models.

Unlike model, things defined with alias are not exported to components; instead, they are expanded at compile time.

Therefore, there are limitations such as:

  • You may not be able to attach annotations.
  • When generating documentation with redocly, Swagger, etc., name information cannot be resolved.
    • Something written as a model would be displayed as NormalUser or SuperUser, but with an alias, it might just be shown as object.
@doc("sample") // => Cannot decorate alias statement.TypeSpec(invalid-decorator-location)
alias Sample = {}

Generics

Generics can be used in TypeSpec's model and alias.

While model and alias could be represented in OpenAPI (albeit redundantly), Generics-style abstraction is not possible in OpenAPI to begin with, so being able to use this is a significant advantage.

One case where Generics is particularly useful is when defining a response structure that is common across all APIs.

model BadRequestErrorResponse {
  @statusCode status: 400;
  @body body: {
    message: string;
  };
}

model SuccessResponse<T> {
  @statusCode status: 200;
  @body body: {
    data: T
  };
}

alias GetResponse<T> = SuccessResponse<T> | BadRequestErrorResponse;

You can declare it as above and then use it like this:

GetResponse<{
  userList: Array<User>
}>

In OpenAPI, you would normally have to write things like BadRequestErrorResponse along with the response status code for every single API (which involves a lot of repetitive and tedious boilerplate!), but having generics makes both writing and maintenance much easier!

Defining an API

Now that we've defined a basic set of schemas, let's use these models and other elements to define an API and export it as OpenAPI.

import "@typespec/http";
import "@typespec/openapi";

using TypeSpec.Http; // By using 'using', TypeSpec.Http is expanded so you can refer to its attributes directly

@service({
  title: "Example API",
})
@TypeSpec.OpenAPI.info({
  version: "1.0",
})
@server("https://api.exapmle.com/v1.0", "production")
@useAuth(
  [
    ApiKeyAuth<ApiKeyLocation.header, "Authorization">
  ]
)
namespace ExampleAPI;

@route("/users")
@tag("User")
namespace UserRoute {
  @summary("Get Users")
  @get
  op users(): GetResponse<{
    users: Array<User>
  }>;
};

Converting this with tsp results in:

openapi: 3.0.0
info:
  title: Example API
  version: "1.0"
tags:
  - name: User
paths:
  /users:
    get:
      tags:
        - User
      operationId: UserRoute_users
      summary: Get Users
      parameters: []
      responses:
        "200":
          description: The request has succeeded.
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: object
                    properties:
                      users:
                        type: array
                        items:
                          anyOf:
                            - $ref: "#/components/schemas/NormalUser"
                            - $ref: "#/components/schemas/SuperUser"
                    required:
                      - users
                required:
                  - data
        "400":
          description: The server could not understand the request due to invalid syntax.
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
                required:
                  - message
security:
  - ApiKeyAuth: []
components:
  schemas:
    NormalUser:
      type: object
      required:
        - name
        - age
      properties:
        name:
          type: string
        age:
          type: number
    SuperUser:
      type: object
      required:
        - role
      properties:
        role:
          type: string
          enum:
            - manager
            - owner
      allOf:
        - $ref: "#/components/schemas/NormalUser"
  securitySchemes:
    ApiKeyAuth:
      type: apiKey
      in: header
      name: Authorization
servers:
  - url: https://api.exapmle.com/v1.0
    description: production
    variables: {}

The OpenAPI Schema is exported in this format. It's great!

File Splitting

OpenAPI doesn't support file splitting natively. Since it's just YAML, you could technically split files and merge them yourself, but you can't have them interpreted in a split state. (This is painful as it makes it harder to get editor support during development.)

In that regard, TypeSpec has a module system that makes it easy to split files, which is another big advantage.

For example, you can split files like this:

response.tsp
namespace Response;

// ...
alias GetResponse<T> = SuccessResponse<T> | BadRequestErrorResponse;
main.tsp
import "./response.tsp";

@route("/users")
@tag("User")
namespace UserRoute {
  @summary("Get Users")
  @get
  op users(): Response.GetResponse<{
    users: Array<User>
  }>;
};

Being able to split files by API tags or other criteria makes maintenance much easier.

Current Limitations and Disappointments

While the overall experience was very good, there were a few points that caught my attention, so I’ll mention them here.

Not All Issues Can Be Detected via Type Errors

First, since it simply outputs OpenAPI, I initially thought that if it could be exported, it would automatically be valid. However, that's not necessarily the case, and it seems that invalid schemas can sometimes be generated.

Therefore, it’s still a good idea to use a linter like redocly that checks the OpenAPI structure. (This is the same as when writing manually, but the point is that using TypeSpec doesn't mean you should skip this step.)

No Support for Webhooks

The most troubling or disappointing part was that I couldn't find a way to describe webhooks (the part of OAS where you define the schema for incoming webhook requests).

In the SwitchBot API, you can register a webhook and receive requests at an arbitrary URL, but since TypeSpec doesn't currently support this, I couldn't include those schemas in the OpenAPI specification.

For my specific use case this time, I just needed to generate a client, and the side receiving the requests didn't matter much to me (even if I defined it in OpenAPI, I wouldn't have used those types to write the handler), so it wasn't critical. However, in cases where you're trying to describe and publish the specifications of an API you're developing yourself using TypeSpec, this could be a bit problematic.

Other than that, there wasn't much else, but due to the nature of TypeSpec exporting OAS, there is a possibility that something supported by OAS but not by TypeSpec might exist, which is a potential downside.

(I didn't dive that deep this time, but) plugin development seems possible and guidance is available in the official documentation, so it might just be a matter of implementing support yourself.

Conclusion

I’ve introduced TypeSpec, which allows you to define OpenAPI relatively easily!

If you are doing schema-first development or need to manually write an OpenAPI Spec because you can't generate it programmatically with a code-first approach, I highly recommend giving it a try.

As a side note, although tasks like this have become much easier with the advent of LLMs, converting HTML or Markdown-based documentation into an OpenAPI Spec (or even just type definitions) is still quite tedious. I really hope that companies providing APIs will offer their documentation via OpenAPI... and that's all for now.

Discussion