# How to model an API in Smithy and emit OpenAPI with smithy-build

> Write a Smithy service with @http bindings and @restJson1, emit OpenAPI 3.1 with smithy build, and catch the shapes the build drops without saying so.

Source: https://voxgig.com/howto/model-in-smithy-and-emit-openapi

- Audience: platform-team
- Level: intermediate
- Verified: 2026-11-30
- Published: 2026-11-30

## Short answer

Model the service, its resources and its operations in Smithy, bind each operation with @http and @httpLabel, and put the @restJson1 protocol trait on the service. Add an openapi plugin block naming the service to smithy-build.json, run smithy validate, then smithy build. The document lands under build/source/openapi. Add a validator for shapes no service reaches, because the build leaves them out without a warning.

---
## You will need

The Smithy CLI. Its Linux release zip, which the
[installation guide](https://smithy.io/2.0/guides/smithy-cli/cli_installation.html) links,
carries its own Java runtime, 25.0.5.1, and its launcher sets `JAVA_HOME` to that runtime, as
`records/versions.txt` shows, so no JDK of yours is used. The CLI downloads the packages named in
`smithy-build.json` from Maven Central on its first run, so the sample's `record.sh` ran it once
and committed what it wrote and printed. Node 22 runs the comparison and the tests over those
files.

## Approaches compared

| Approach | When it fits | What it costs you | When to pick something else |
| --- | --- | --- | --- |
| [hand-written OpenAPI](https://spec.openapis.org/oas/v3.1.0.html) | One team, one API, and the document is the contract everybody already reads | Every naming and protocol rule lives in a linter config, applied after the fact | Several teams edit one API and the rules must hold before a document exists |
| [Smithy (`smithy build` with the `openapi` plugin)](https://smithy.io/2.0/guides/model-translations/converting-to-openapi.html) | Many teams and services, with rules enforced in the model by validators | A JVM toolchain, Maven downloads at build time, and a REST protocol from the `aws.protocols` namespace | Your team writes TypeScript and wants the toolchain on npm |
| [TypeSpec](https://typespec.io/docs/emitters/openapi3/reference/emitter/) | A team that wants a compact language and an npm toolchain | Generated operation ids such as `Invoices_listInvoices` unless you configure them, and emitter options to learn | Your organization already shares Smithy models and validators across services |

Smithy's cost is the toolchain: a Java runtime, a download from Maven Central on the first build,
and a REST protocol trait that lives in the AWS namespace. TypeSpec installs from npm and
compiles the same API, though its emitter keeps unused models unless told not to.
Hand-written OpenAPI needs no build at all, at the price of checking every rule after the
document is written.

## Model the service and its HTTP bindings

The service names its protocol and its resources. The resource names the operations that read,
list and create it:

```smithy title="model/invoices.smithy"
$version: "2"

namespace example.invoices

use aws.protocols#restJson1

/// Create and read invoices.
@restJson1
@title("Invoices")
service Invoices {
    version: "2026-11-29"
    resources: [Invoice]
}

resource Invoice {
    identifiers: { invoiceId: InvoiceId }
    read: GetInvoice
    list: ListInvoices
    create: CreateInvoice
}

/// An invoice id, such as inv_8f3k2.
@pattern("^inv_[a-z0-9]+$")
string InvoiceId

/// Returns one invoice by its id.
@readonly
@http(method: "GET", uri: "/invoices/{invoiceId}")
operation GetInvoice {
    input := {
        @required
        @httpLabel
        invoiceId: InvoiceId
    }
```

[`@http`](https://smithy.io/2.0/spec/http-bindings.html#http-trait) gives the method and the
URI pattern, and [`@httpLabel`](https://smithy.io/2.0/spec/http-bindings.html#httplabel-trait)
binds the member to the `{invoiceId}` segment. `@restJson1` is the
[AWS restJson1 protocol](https://smithy.io/2.0/aws/protocols/aws-restjson1-protocol.html), which
the `smithy-aws-traits` package defines.

## Emit OpenAPI with smithy-build

The plugin block names the service, and `smithy-build.json` names the two packages the build
needs:

```json title="smithy-build.json"
{
  "version": "1.0",
  "sources": ["model"],
  "maven": {
    "dependencies": [
      "software.amazon.smithy:smithy-aws-traits:1.75.1",
      "software.amazon.smithy:smithy-openapi:1.75.1"
    ]
  },
  "plugins": {
    "openapi": {
      "service": "example.invoices#Invoices",
      "version": "3.1.0",
      "useIntegerType": true
    }
  }
}
```

The plugin writes OpenAPI 3.0.2 unless
[`version`](https://smithy.io/2.0/guides/model-translations/converting-to-openapi.html#generate-openapi-setting-version)
says 3.1.0. Without
[`useIntegerType`](https://smithy.io/2.0/guides/model-translations/converting-to-openapi.html#generate-openapi-setting-useintegertype),
`Integer` and `Long` members come out as `"type": "number"`, all five of them in a control build
that `records/integer-type.txt` keeps. Run the two commands from the directory that holds
`smithy-build.json`:

```bash
smithy validate
smithy build --output build
```

`record.sh` ran them on Smithy CLI 1.75.1 and kept what they printed:

```bash
cat records/smithy-build.txt
```

```text output
$ smithy validate
SUCCESS: Validated 430 shapes

exit 0
$ smithy build --output build
SUCCESS: Validated 430 shapes

Validated model, now starting projections...

──  source  ────────────────────────────────────────────────────────────────────
Completed projection source (430): build/source

Summary: Smithy built 1 projection(s), 4 plugin(s), and 6 artifacts
exit 0
```

The document is `build/source/openapi/Invoices.openapi.json`, committed as
`openapi/smithy.openapi.json`.

## Compile the same API in TypeSpec

The TypeSpec version of the service is one file with an interface of three operations, and a
config file that picks the OpenAPI emitter and the version:

```yaml title="typespec/tspconfig.yaml"
emit:
  - "@typespec/openapi3"
options:
  "@typespec/openapi3":
    openapi-versions:
      - "3.1.0"
    emitter-output-dir: "{output-dir}"
```

`tsp compile main.tsp --output-dir out` wrote `out/openapi.yaml` in the same `record.sh` run,
from four npm packages at 1.18.0 and no other runtime than Node. Two defaults differ from
Smithy's. Operation ids join the interface name and the operation name, as in
`Invoices_listInvoices`, where Smithy uses the shape name `ListInvoices`. And every model
declared in the service namespace is emitted, whether an operation uses it or not, so a stray
model reaches the document instead of vanishing from it. The emitter reference lists an
`operation-id-strategy` option for the first default and `omit-unreachable-types` for the second.

## Check it worked

`compare.mjs` reads the Smithy document, the TypeSpec one and the hand-written one, and lints
all three with the `spectral:oas` ruleset of Spectral:

```bash
node compare.mjs
```

```text output
smithy (openapi/smithy.openapi.json), OpenAPI 3.1.0
  operations: GET /invoices ListInvoices; GET /invoices/{invoiceId} GetInvoice; POST /invoices CreateInvoice
  schemas:    CreateInvoiceRequestContent, CreateInvoiceResponseContent, GetInvoiceResponseContent, InvoiceNotFoundResponseContent, InvoiceSummary, ListInvoicesResponseContent
  "type": "integer" 5 times, "type": "number" 0 times
  spectral:oas errors 0, rules reported: info-contact, oas3-api-servers, operation-tags
typespec (openapi/typespec.openapi.yaml), OpenAPI 3.1.0
  operations: GET /invoices Invoices_listInvoices; GET /invoices/{invoiceId} Invoices_getInvoice; POST /invoices Invoices_createInvoice
  schemas:    AuditEntry, Invoice, InvoiceId, InvoiceNotFound, InvoiceSummary
  "type": "integer" 4 times, "type": "number" 0 times
  spectral:oas errors 0, rules reported: info-contact, oas3-api-servers, oas3-unused-component, operation-tags
hand-written (handwritten/openapi.yaml), OpenAPI 3.1.0
  operations: GET /invoices ListInvoices; GET /invoices/{invoiceId} GetInvoice; POST /invoices CreateInvoice
  schemas:    AuditEntry, Invoice, InvoiceId, InvoiceNotFound, InvoiceSummary
  "type": "integer" 4 times, "type": "number" 0 times
  spectral:oas errors 0, rules reported: info-contact, oas3-api-servers, oas3-unused-component, operation-tags
```

All three describe the same three routes with no Spectral error. Smithy names its schemas after
operations, such as `GetInvoiceResponseContent`, where the other two name them after models. The
TypeSpec source and the hand-written document both declare an `AuditEntry` model that no
operation uses, and both documents carry it. The Smithy document does not, for the reason in the
next section.[^1]

```bash
node --test emit.test.mjs
```

```text output
1..9
# tests 9
# suites 0
# pass 9
# fail 0
# cancelled 0
# skipped 0
# todo 0
# duration_ms 911.092672
```

## When it goes wrong

The model validates and the build fails. `record.sh` deleted the `@restJson1` line and ran both
commands again:

```bash
cat records/no-protocol.txt
```

```text output
$ diff model/invoices.smithy no-protocol/model/invoices.smithy
8d7
< @restJson1
$ smithy validate
SUCCESS: Validated 430 shapes

exit 0
$ smithy build --output build
SUCCESS: Validated 430 shapes

Validated model, now starting projections...


Projection source failed: software.amazon.smithy.openapi.OpenApiException: No Smithy protocol was configured and `example.invoices#Invoices` does not define any protocols.
software.amazon.smithy.openapi.OpenApiException: No Smithy protocol was configured and `example.invoices#Invoices` does not define any protocols.

Summary: Smithy built 0 projection(s), 0 plugin(s), and 0 artifacts

The following 1 Smithy build projection(s) failed: [source]

exit 1
```

A protocol is optional to the model and required by the converter. In 1.75.1 its
[core extension](https://github.com/smithy-lang/smithy/blob/1.75.1/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/CoreExtension.java)
registers a restJson1 converter beside an RPC v2 JSON one. Put `@restJson1` back, or set the
[`protocol`](https://smithy.io/2.0/guides/model-translations/converting-to-openapi.html#generate-openapi-setting-protocol)
setting when the service carries more than one.

The build succeeds and a shape is missing. `record.sh` added `variants/audit-entry.smithy`, a
structure no operation uses, and took the validators out:

```bash
cat records/orphan.txt
```

```text output
$ smithy validate
SUCCESS: Validated 433 shapes

exit 0
$ smithy build --output build
SUCCESS: Validated 433 shapes

Validated model, now starting projections...

──  source  ────────────────────────────────────────────────────────────────────
Completed projection source (433): build/source

Summary: Smithy built 1 projection(s), 4 plugin(s), and 6 artifacts
exit 0
AuditEntry in the build model.json: true
AuditEntry in the OpenAPI document: false
OpenAPI document identical to the build without AuditEntry: true
$ smithy build --output build-keep
SUCCESS: Validated 433 shapes

Validated model, now starting projections...

──  source  ────────────────────────────────────────────────────────────────────
Completed projection source (433): build-keep/source

Summary: Smithy built 1 projection(s), 4 plugin(s), and 6 artifacts
exit 0
with keepUnusedComponents, AuditEntry in the OpenAPI document: false
```

The converter starts from the service and converts only the shapes it can reach, as a comment
in [`OpenApiConverter.java`](https://github.com/smithy-lang/smithy/blob/1.75.1/smithy-openapi/src/main/java/software/amazon/smithy/openapi/fromsmithy/OpenApiConverter.java#L224-L225)
states. `keepUnusedComponents` does not bring the shape back, because it keeps components the
converter made, and this shape never became one. Connect the shape to an operation, or make its
absence an error with a validator:

```smithy title="model/validators.smithy"
    {
        name: "EmitEachSelector"
        id: "UnreachableShape"
        message: "No service reaches this shape, so the openapi plugin leaves it out."
        severity: "DANGER"
        configuration: {
            selector: "[id|namespace = 'example.invoices'] :not(service) :not(member) :not(:in(:root(service ~> *)))"
        }
    }
```

[`EmitEachSelector`](https://smithy.io/2.0/spec/model-validation.html#emiteachselector) emits
one event per shape the selector matches, and the
[`:root` function](https://smithy.io/2.0/spec/selectors.html#selector-root-function) evaluates
`service ~> *` against the whole model, so the selector matches every shape in the namespace that
no service reaches. With the validators in place, the same model fails `smithy validate`:

```bash
cat records/orphan-validated.txt
```

```text output
$ smithy validate

──  DANGER  ─────────────────────────────────────────────────── UnreachableShape
Shape: example.invoices#AuditEntry
File:  model/audit-entry.smithy:7:1

5| /// A change to an invoice, kept for audit. No operation uses it.
6| @references([{ resource: Invoice }])
7| structure AuditEntry {
 | ^

No service reaches this shape, so the openapi plugin leaves it out.

FAILURE: Validated 433 shapes (DANGER: 1)

exit 1
```

## When not to do this

Do not adopt Smithy for one service owned by one team. The JVM toolchain, the Maven download and
the AWS-namespaced protocol buy governance across teams, and a single team gets the same checks
from a hand-written document and a Spectral ruleset.

Skip Smithy when the people who own the API write TypeScript and nothing else. TypeSpec compiled
this API from npm packages alone, and its
[`omit-unreachable-types`](https://typespec.io/docs/emitters/openapi3/reference/emitter/) option
drops unused models, as `records/typespec.txt` shows.

Do not expect the OpenAPI document to carry everything the model says. The
[conversion guide](https://smithy.io/2.0/guides/model-translations/converting-to-openapi.html#unsupported-features)
says information is lost in the conversion and lists the features it does not support. Keep
the Smithy model as the source and treat the document as build output.

## Related how-tos

- [Describe payloads in JSON Schema alone and generate types](/howto/json-schema-alone-as-api-description)

- [Define a gRPC service in a proto3 file](/howto/define-a-grpc-service-in-proto3)

- [Gate a pull request on OpenAPI lint results](/howto/gate-a-pull-request-on-openapi-lint)

- [Reuse schemas and responses with components and $ref](/howto/reuse-schemas-with-components-and-ref)

- [Get lint feedback on an OpenAPI file while you edit it](/howto/lint-openapi-while-you-edit)

## Last verified

Verified 2026-11-30 against the Smithy CLI 1.75.1 Linux zip with `smithy-openapi` and
`smithy-aws-traits` 1.75.1, `@typespec/compiler`, `@typespec/http`, `@typespec/openapi` and
`@typespec/openapi3` 1.18.0, `@stoplight/spectral-cli` 6.17.1 and Node 22.23.5. The Smithy and
TypeSpec runs happened once in `record.sh`. The output blocks print the records it committed, and
`compare.mjs` and the tests read those files.

[^1]: Both tools have a word for an unused component. The `oas3-unused-component` warning of Spectral
fires on the hand-written and TypeSpec documents because they carry `AuditEntry`, and the
[Smithy conversion guide](https://smithy.io/2.0/guides/model-translations/converting-to-openapi.html#generate-openapi-setting-keepunusedcomponents)
offers `keepUnusedComponents` to stop unused components being removed. A shape outside the
service closure is neither, since it never became a component to keep or to warn about.