How-to › Describe your API

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.

Audience
Platform team
Level
intermediate
Topic
Describe an API without OpenAPI
Verified

Your Smithy model validates, but smithy build prints a failed projection and writes no OpenAPI document, because the service has no protocol trait. Or the build succeeds, and a structure your team added to the model is missing from the document that the SDK and the docs are generated from. The build printed no warning about the missing structure.

What you get

You will end up with a Smithy model of one service, a smithy-build.json that emits OpenAPI 3.1, and a validator that fails any shape the document cannot reach. This is for you if several teams write one API and OpenAPI is the output, not the source.

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 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

ApproachWhen it fitsWhat it costs youWhen to pick something else
hand-written OpenAPIOne team, one API, and the document is the contract everybody already readsEvery naming and protocol rule lives in a linter config, applied after the factSeveral teams edit one API and the rules must hold before a document exists
Smithy (smithy build with the openapi plugin)Many teams and services, with rules enforced in the model by validatorsA JVM toolchain, Maven downloads at build time, and a REST protocol from the aws.protocols namespaceYour team writes TypeScript and wants the toolchain on npm
TypeSpecA team that wants a compact language and an npm toolchainGenerated operation ids such as Invoices_listInvoices unless you configure them, and emitter options to learnYour 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:

$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 gives the method and the URI pattern, and @httpLabel binds the member to the {invoiceId} segment. @restJson1 is the AWS restJson1 protocol, 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:

{
  "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 says 3.1.0. Without 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:

smithy validate
smithy build --output build

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

cat records/smithy-build.txt
$ 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:

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:

node compare.mjs
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

node --test emit.test.mjs
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:

cat records/no-protocol.txt
$ 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 registers a restJson1 converter beside an RPC v2 JSON one. Put @restJson1 back, or set the 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:

cat records/orphan.txt
$ 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 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:

    {
        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 emits one event per shape the selector matches, and the :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:

cat records/orphan-validated.txt
$ 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 option drops unused models, as records/typespec.txt shows.

Do not expect the OpenAPI document to carry everything the model says. The conversion guide 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.

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.

Footnotes

  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 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. ↩︎ Back to text

Read this page as markdown · All how-to guides

Generate the client instead of writing it#

Retries, timeouts, pagination and auth are the same problems in every client. Voxgig generates them from your OpenAPI description, in 23 languages, from one model.

Listen to Fireside, the Voxgig podcast

Since 2018, Richard Rodger has talked with developer advocates, event organizers, and the people who build developer-facing companies about the specifics of the work.