Skip to content

OpenAPI3 to TypeSpec

Converting OpenAPI 3 into TypeSpec

This package includes the tsp-openapi3 CLI for converting OpenAPI 3 specs into TypeSpec. The generated TypeSpec depends on the @typespec/http, @typespec/openapi and @typespec/openapi3 libraries.

Usage

  1. via the command line
Terminal window
tsp-openapi3 ./openapi3spec.yml --output-dir ./tsp-output

tsp-openapi3 arguments

The path to the OpenAPI3 yaml or json file must be passed as a position argument.

The named arguments are:

NameTypeRequiredDescription
output-dirstringrequiredThe output directory for generated TypeSpec files. Will be created if it does not exist.
helpbooleanoptionalShow help.

Examples

1. Convert component schemas into models

All schemas present at #/components/schemas will be converted into a model or scalar as appropriate.

OpenAPI3 TypeSpec
components:
schemas:
Widget:
type: object
required:
- id
- weight
- color
properties:
id:
type: string
weight:
type: integer
format: int32
color:
type: string
enum:
- red
- blue
uuid:
type: string
format: uuid
model Widget {
id: string;
weight: int32;
color: "red" | "blue";
}
@format("uuid")
scalar uuid extends string;

2. Convert component parameters into models or fields

All parameters present at #/components/parameters will be converted to a field in a model. If the model doesnโ€™t exist in #/components/schemas, then it will be created.

OpenAPI3 TypeSpec
components:
parameters:
Widget.id:
name: id
in: path
required: true
schema:
type: string
schemas:
Widget:
type: object
required:
- id
- weight
- color
properties:
id:
type: string
weight:
type: integer
format: int32
color:
type: string
enum:
- red
- blue
model Widget {
@path id: string;
weight: int32;
color: "red" | "blue";
}
components:
parameters:
Foo.id:
name: id
in: path
required: true
schema:
type: string
model Foo {
@path id: string;
}

3. Convert path routes to operations

All routes using one of the HTTP methods supported by @typespec/http will be converted into operations at the file namespace level. A model is also generated for each operation response.

At this time, no automatic operation grouping under interfaces is performed.

OpenAPI3 TypeSpec
paths:
/{id}:
get:
operationId: readWidget
parameters:
- name: id
in: path
required: true
schema:
type: string
responses:
"200":
description: The request has succeeded.
content:
application/json:
schema:
$ref: "#/components/schemas/Widget"
/**
* The request has succeeded.
*/
model readWidget200ApplicationJsonResponse {
@statusCode statusCode: 200;
@bodyRoot body: Widget;
}
@route("/{id}") @get op readWidget(@path id: string): readWidget200ApplicationJsonResponse;