How-to › Ship an SDK

How to write a new language generator for a Lua SDK#

Write the Lua mapping down, emit it as your own sdkgen target with a pluggable transport and a rockspec, and prove it on Lua 5.1 and 5.4 against recorded replies.

Audience
Library maintainer
Level
advanced
Topic
Target another language
Languages
Lua and TypeScript
Verified

Read first: Evaluate a third-tier SDK target before you ship it

Your SDK has to run inside OpenResty, which embeds LuaJIT and its Lua 5.1 dialect. sdkgen’s bundled lua target declares lua >= 5.3 in its rockspec. OpenAPI Generator’s lua generator emits one function per endpoint over lua-http. Patching either output lasts until the next regeneration.

What you get

You will end up with a Lua target of your own that emits a client for Lua 5.1 to 5.4, with the HTTP library behind one function and a rockspec. This is for you if a generated Lua client has to fit a runtime its generator did not plan for.

Short answer

In sdkgen, add a target of your own. Give it a model file under .sdk/model/target/, a Main component that turns each operation into a Lua function returning data, err, and a one-function transport bound to LuaSocket. Emit a rockspec that pins lua >= 5.1, < 5.5, generate twice, compare the bytes, and run the client on each interpreter.

You will need

Node 22 or later, an OpenAPI 3 document, and every interpreter you intend to claim. This page uses the Bookshelf document and runs the client on Lua 5.4.6 and on Lua 5.1.5 built from lua.org, the version LuaJIT’s extensions page calls LuaJIT fully upwards-compatible with. Read the prerequisite on third-tier targets first.

sdkgen 4.44.3 bundles a lua target: entity-shaped, with nil, err returns and LuaSocket behind utility.fetcher. This page adds a second target, lua-lite, because the runtime range is the thing that does not fit.

Approaches compared

ApproachWhen it fitsWhat it costs youWhen to pick something else
OpenAPI Generator lua generatorLua 5.2 or later with lua-http, and one function per endpoint suits callersA beta generator, reshaped by overriding its Mustache templates rather than through a mappingOpenResty, Lua 5.1, or entity-shaped calls
OpenAPI Generator meta command scaffoldingA team that already maintains Java generators and wants full controlRebuilds the language layer from a Java class, and the parser’s naming stays operationId-drivenYou want the operations already grouped and typed
orvalYour other clients are TypeScript and Lua is the one gapNo Lua output at all, so Lua needs a second generator beside itLua is the main target
the sdkgen custom target routeSeveral targets from one model, and you will own one moreTies your target to sdkgen’s model shape, and doctor flags your target’s own filesYou want a standalone generator with no upstream

Voxgig maintains sdkgen. It is the subject of this page and one of four options in the table, not the recommendation.

Reusing sdkgen’s model saves the parsing and the classification, and ties the target to that model’s shape. A meta generator owes nothing to sdkgen and rebuilds the language layer in Java. orval writes TypeScript only, so it is a neighbor here, not a route.

Write the language mapping down first

Decide each of these before writing a line of the component. The component then encodes them, and mapping.ts keeps the reusable ones testable on their own.

  • Type names: $STRING, $INTEGER, $NUMBER and $BOOLEAN become string, integer, number and boolean in Lua language server ---@field annotations.
  • Reserved words: the 22 of Lua 5.4.1 A name that is one, or is not an identifier, is indexed, Client["end"], never written Client.end.
  • String escaping: every emitted literal escapes quote, backslash, control bytes and bytes over 126 as three-digit \ddd, which Lua 5.1 already reads.
  • Module naming: one module named after the project, bookshelf, and its runtime under it, bookshelf.json and bookshelf.luasocket.
  • Returns: every operation returns data, err and never raises; err.kind is param, http, transport, encode or decode.
  • Transport: transport(request) returns response, err, with plain tables on both sides.

Emit the client from the model

The target’s model file switches every standard phase off, as a tool target does, so Main writes the whole package. Each operation reaches the component already classified, with its path split into literal and variable segments:

        const arg = point.bf ? 'data' : 'match'
        const parts: string[] = []
        const checks: string[] = []
        for (const s of point.s || []) {
          if (null != s.lit) parts.push(luastr('/' + s.lit))
          else {
            const v = '_' + s.var.replace(/[^A-Za-z0-9_]/g, '_')
            checks.push(`  local ${v}, ${v}_err = segment(${arg}[${luastr(s.var)}], ${luastr(s.var)})\n` +
              `  if not ${v} then return nil, ${v}_err end\n`)
            parts.push(luastr('/'), v)
          }
        }

What it writes for GET /books/{bookId}:

Book.load = function(self, match)
  match = match or {}
  local _id, _id_err = segment(match["id"], "id")
  if not _id then return nil, _id_err end
  return self.client:call("GET", "/books" .. "/" .. _id, nil)
end

The model already renamed bookId to id, so every target’s callers write load({ id = ... }). segment percent-encodes the value and refuses "", . and .. before any request.

Bind the transport and emit a rockspec

The component copies two runtime files: a JSON encoder and decoder in Lua 5.1 syntax, so the client needs no JSON rock, and the LuaSocket binding. The binding calls socket.http.request with an ltn12 source and sink, and switches to LuaSec’s ssl.https for an https URL. The rockspec pins one interpreter range, LuaSocket, and LuaSec, using the special lua dependency the rockspec format reserves for the interpreter version:

dependencies = {
  "lua >= 5.1, < 5.5",
  "luasocket >= 3.0",
  "luasec >= 1.0",
}

Run it against a recorded response

client_test.lua builds a client with a transport that records each request and replies from the files in recorded/, then checks each part of the mapping.

lua5.4 client_test.lua
ok   list returns the recorded book: Emma
ok   published decodes as a number: 1815
ok   a 404 is nil, err with status 404
ok   an id is one escaped segment: https://api.example.com/v1/books/b%2F1
ok   an id of .. is refused before any request: param
ok   an empty id and an id of . are refused too: param param
ok   create sends JSON: {"published":1817,"title":"Persuasion"}
ok   a transport failure is returned, not raised: connection refused
Lua 5.4, all checks passed

generate.sh ran the same file on Lua 5.1.5 and kept its output in generated/run-lua5.1.txt; its last line is Lua 5.1, all checks passed.

Compare the OpenAPI Generator Lua client and the orval options

OpenAPI Generator 7.27.0 printed Generator 'lua' is considered beta for the same document. inspect.mjs reads both clients.

node inspect.mjs
sdkgen lua-lite
  calls:    Client.book Book.create Book.list Book.load Book.remove Book.update M.new Client:call
  requires: bookshelf.json bookshelf.luasocket
  rockspec: lua >= 5.1, < 5.5 | luasocket >= 3.0 | luasec >= 1.0
  one book: self.client:call("GET", "/books" .. "/" .. _id
OpenAPI Generator lua
  calls:    default_api:create_book default_api:delete_book default_api:get_book default_api:list_books default_api:update_book
  requires: http.request http.util dkjson basexx openapiclient.model.book
  rockspec: lua >= 5.2 | http | dkjson | basexx
  one book: string.format("%s/books/%s", self.basePath, book_id)
generate run 1: 112 files, run 2: 112 files, byte changes: 0

Its get_book formats book_id into the path without escaping it, so an id of b/1 asks for a different path. Its version floor is a template, not Java. author template -g lua writes the built-in templates, the lua >= 5.2 line sits in luarocks.mustache, and generate -t with an edited copy wrote lua >= 5.1, < 5.5, the user-defined templates route OpenAPI Generator’s customization page describes. Replacing lua-http means rewriting api.mustache too, and a meta generator class is the step past that.

orval has no Lua output. Its client option takes seventeen values, from angular to mcp, all TypeScript output, or a function that builds a client from orval’s own generators. A team that keeps orval for its TypeScript client generates the Lua one from the same document with either route on this page.

Check it worked

Generate twice from a clean scaffold and compare every output byte, then run the client. The last line of the inspect.mjs output is the first half, and a second scaffold built from scratch wrote the same 112 fingerprints. The tests cover the rest.

node --test lua.test.mjs
# tests 7
# suites 0
# pass 7
# fail 0

One test runs lua5.4 and fails unless it prints Lua 5.4, all checks passed. Another emits a string with a quote, a backslash, a newline before a digit and an accented letter, and checks Lua reads it back unchanged.

When it goes wrong

A literal reads back wrong. A decimal escape without padding, \10 before a 5, reads as \105, the letter i. Pad every escape to three digits, as luastr does.

The client fails on the first user’s runtime. Lua 5.1 has no goto, no // and no utf8 library, so the runtime files are written in 5.1 syntax and the rockspec says so. Under OpenResty, pass a transport built on its cosocket API rather than the LuaSocket binding.

The target writes an endpoint function where the model holds an entity. Read point.s and the op name from the model; parsing the path again in the component rebuilds what apidef did.

When not to do this

Do not write your own target if the bundled sdkgen lua target fits your interpreter. It carries the full pipeline, features and test corpus, which lua-lite does not.

Leave sdkgen out if Lua is your only client. The OpenAPI Generator lua generator is the better choice on Lua 5.2 or later with lua-http, and a hand-written client is smaller still for a handful of endpoints.

Do not claim OpenResty until you have run the client inside it.2 This page ran Lua 5.1.5, the dialect LuaJIT follows, and not LuaJIT itself.

Last verified

Verified 2026-11-20 against Node 22.23.5, @voxgig/create-sdkgen 0.31.9, @voxgig/sdkgen 4.44.3, OpenAPI Generator 7.27.0, Lua 5.4.6 and Lua 5.1.5. Every output block is what the command preceding it printed. Generation ran in generate.sh, including OpenAPI Generator with an overridden luarocks.mustache. OpenResty and LuaJIT were not run, LuaSocket and LuaSec were not installed, so the binding was not exercised, and orval was not run because it has no Lua output.

Footnotes

  1. The Lua 5.1 manual reserves 21 words. The Lua 5.2 manual adds goto, so a 5.1 program with a variable of that name stops parsing on every later Lua. The mapping reserves all 22, which costs a 5.1 caller one name: a field called goto is indexed as ["goto"]. ↩︎ Back to text

  2. The lua-nginx-module README says the module embeds LuaJIT 2.0 or 2.1 and is a core component of OpenResty. Since its version v0.10.16 the standard Lua interpreter, PUC-Rio Lua, is not supported, so a client tested only on PUC-Rio Lua has not met the interpreter OpenResty runs. ↩︎ 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.