# How to give a Lua SDK nil, err returns and an injected transport

> Make every Lua SDK call return value, nil or nil, err, and inject the transport so it runs on LuaSocket and lua-http, with lua-resty-http tested on a stand-in.

Source: https://voxgig.com/howto/lua-sdk-nil-err-and-transport-choice

- Audience: api-producer
- Level: intermediate
- Languages: lua
- Verified: 2026-11-22
- Published: 2026-11-22

## Short answer

Make every Lua SDK call return value, nil or nil, err, where err is a table with a kind, and raise only for a mistake in the calling code. Take options as one table, the transport among them: a function that takes a request table and returns a response table or nil, err. Write one transport each for LuaSocket, lua-http and lua-resty-http, and build the client without opening a connection so OpenResty's init phase can create it.

---
## You will need

Lua 5.4, and LuaSocket, lua-http, or OpenResty with lua-resty-http for live requests. Verified
2026-11-22 against Lua 5.4.6 and 5.1.5, LuaSocket 3.1.0, lua-http 0.4, busted 2.2.0, OpenAPI
Generator 7.27.0, and @voxgig/sdkgen 4.44.3. The document, `api.json`, describes a Pantry API with
four operations behind a bearer token. Constructor options follow
[Design an SDK constructor that takes configuration once](/howto/sdk-client-constructor-and-configuration).

## Approaches compared

| Approach | When it fits | What it costs you | When to pick something else |
| --- | --- | --- | --- |
| [lua-http](https://daurnimator.github.io/lua-http/0.4/) | Plain Lua that wants HTTP/2, TLS, and a non-blocking `cqueues` loop | C modules to install, `cqueues`, `luaossl` and `lpeg` among them, and an event loop of its own | You run inside OpenResty or want one small dependency |
| [lua-resty-http](https://github.com/ledgetech/lua-resty-http) | OpenResty, where cosockets keep the worker from blocking | Runs only inside OpenResty, and only in the phases that allow cosockets | The SDK also has to run under plain Lua |
| [LuaSocket](https://lunarmodules.github.io/luasocket/http.html) | Plain Lua 5.1 to 5.4, scripts and CLIs | A blocking call, and a `TIMEOUT` that is a module global, shared with all code in the process | You serve requests in OpenResty, where cosockets keep network calls non-blocking |
| [OpenAPI Generator lua](https://openapi-generator.tech/docs/generators/lua/) | A Lua client in minutes, with lua-http already installed | A beta generator with lua-http hardcoded, no bearer support, and ids put in paths as given | You need OpenResty, a bearer token, or callers' ids in paths |
| [sdkgen Lua target](https://github.com/voxgig/sdkgen) | The API owner already ships sdkgen SDKs, on Lua 5.3 or later | Needs Lua 5.3 or later, so no OpenResty, and a transport's error string arrives with an empty `code` | You target LuaJIT or OpenResty |
| [`swift-openapi-generator`](https://swiftpackageindex.com/apple/swift-openapi-generator/1.14.4/documentation/swift-openapi-generator) | The same API also needs a Swift client with a pluggable transport | Writes Swift only, so it gives a Lua SDK nothing but its design | Lua is the only client you ship |

Voxgig maintains sdkgen. It is one of six rows here and has no claim on the choice.

The three libraries are the transports, and the hand-written SDK keeps them interchangeable at
the price of a contract you maintain. Both generators answer in less code: OpenAPI Generator ties
its client to lua-http, and sdkgen gives you a fetch seam on Lua 5.3 or later only.

## Return nil, err and raise only for mistakes

[Programming in Lua](https://www.lua.org/pil/8.3.html) gives the rule: an exception that is easily
avoided should raise an error, and otherwise the function returns an error code.[^1] A 404, a
refused connection and a body that is not JSON cannot be avoided by the caller. A missing transport
can, so `pantry.new` raises at the caller's line.

```lua title="pantry/init.lua"
function Client:request(method, path, body)
  local headers = { accept = "application/json" }
  if self.token then headers.authorization = "Bearer " .. self.token end
  local payload
  if body ~= nil then
    payload = json.encode(body)
    headers["content-type"] = "application/json"
    headers["content-length"] = tostring(#payload)
  end
  -- A transport that raises is a failed request too, so pcall turns the raise into an err.
  local ok, res, terr = pcall(self.transport, {
    method = method, url = self.base .. path, headers = headers, body = payload, timeout = self.timeout,
  })
  if not ok then return fail("transport", "the transport raised: " .. tostring(res)) end
  if res == nil then return fail("transport", tostring(terr or "the transport returned nothing")) end
  if type(res) ~= "table" then return fail("transport", "the transport returned a " .. type(res)) end
  if type(res.status) ~= "number" or res.status ~= math.floor(res.status) then
    return fail("transport", "the transport returned no status")
  end
  if res.body ~= nil and type(res.body) ~= "string" then
    return fail("transport", "the transport returned a " .. type(res.body) .. " body")
  end
  if res.status < 200 or res.status > 299 then
    return fail("http", "the API refused " .. method .. " " .. path, { status = res.status, body = res.body })
  end
  local value, _, derr = json.decode(res.body or "", 1, nil)
  if derr ~= nil then return fail("decode", "the body is not JSON: " .. tostring(derr)) end
  if value == nil then return fail("decode", "the body is JSON null") end
  return value, nil
end
```

`err.kind` is one of `param`, `transport`, `http` and `decode`, so a caller branches on a string
rather than on message text. A bad argument to a call is `param` and not a raise, because an id or
a quantity often comes from outside the program. `get_item` escapes the id as one path segment
and refuses `""`, `.` and `..`. A transport that raises, or returns something other than a
response table, becomes a `transport` error.

## Put the HTTP library behind one function

The transport is the whole contract: a request table in, a response table with `status`,
`headers` and `body` out, or `nil, err`. The OpenResty one checks the phase first, because
[lua-nginx-module](https://github.com/openresty/lua-nginx-module#ngxsockettcp) lists the phases
where `ngx.socket.tcp` may run, and `init` is not among them.[^2]

```lua title="pantry/transport/resty.lua"
return function()
  return function(request)
    local phase = ngx.get_phase()
    if not COSOCKET_PHASES[phase] then
      return nil, "resty: cosockets are not available in the " .. phase .. " phase"
    end
    local httpc, err = http.new()
    if not httpc then return nil, "resty: " .. tostring(err) end
    httpc:set_timeout(request.timeout * 1000)
```

`http.new()` runs on every request and never in `pantry.new`, because
[lua-nginx-module](https://github.com/openresty/lua-nginx-module#ngxsockettcp) gives a cosocket
the lifetime of the Lua handler that created it. The LuaSocket transport passes no `create`
function, because LuaSocket picks LuaSec for an `https` URL only when given none.

`record-responses.mjs` sent each request once to `server.mjs`, a stand-in held to `api.json`, and
wrote the answers to `recorded/responses.lua`. Stand-ins for the three libraries replay it, so the
page's commands need no C module.

```bash
lua5.4 demo.lua
```

```text output
luasocket
  list_items()                 {itm_1, itm_2, itm_3}, nil
  list_items({shelf = 'B2'})   {itm_3}, nil
  get_item('itm_2')            itm_2 Basmati rice, nil
  get_item('nope')             nil, pantry: http 404: the API refused GET /items/nope (kind http)
  get_item('..')               nil, pantry: param: not an item id: ".." (kind param)
  create_item(...)             itm_4 Lentils, nil
```

The `resty` and `luahttp` blocks print the same six lines. `record.sh` ran the SDK through the
real LuaSocket on Lua 5.4 and 5.1 and the real lua-http on 5.1, and a test compares each record
with the stand-in run line by line. It also ran `spec/` under
[busted](https://lunarmodules.github.io/busted/), which runs the LuaSocket and OpenResty
transports over the stand-ins against the one recording:

```text title="records/busted.txt"
busted 2.2.0 on Lua 5.1.5
ok 1 - luasocket transport returns the recorded list as items, nil
ok 2 - luasocket transport returns nil and an http error for the recorded 404
ok 3 - luasocket transport returns nil and a transport error for a refused connection
```

## Read the error and transport of each generated client

`generate.sh` ran sdkgen's `lua` target and OpenAPI Generator's `lua` generator on `api.json`.

```bash
lua5.4 generated.lua
```

```text output
sdkgen lua target, through system.fetch and the resty transport
  Item():list()                  3 entities, nil
  Item():load({id = 'nope'})     nil, err{code="request_status", status=404, msg="PantrySDK: load: request: 404: Error"}
  Item():list(), refused         nil, err{code="", status=-1, msg="PantrySDK: list: resty: connection refused"}
  Item():load({id = '../shelves'}) sent GET /v1/items/..%2Fshelves, nil, err{code="request_status", status=404, msg="PantrySDK: load: request: 404: Error"}
  Item():list(), refused, coded  nil, err{code="transport", status=-1, msg="PantrySDK: list: resty: connection refused"}
openapi-generator lua
  get_item('itm_2'), no token     nil, "401", "{\"error\":\"unauthorized\"}"
  list_items(nil)                raised
  get_item('../shelves'), no token nil, "401", "{\"error\":\"unauthorized\"}"
  get_item('itm_2'), wrapped      itm_2 Basmati rice
  get_item('nope'), wrapped       nil, "404", "{\"error\":\"no such item\"}"
  get_item('../shelves'), wrapped 2 shelves cast as an item, id nil
```

sdkgen returns `nil, err` too, and its `system.fetch` option is a transport seam that took this
page's OpenResty transport through a short adapter in `generated.lua`. A string error from the
adapter arrives with an empty `code`, and a `PantryError` from `core.error` keeps its code. Its
code uses the bit shifts of Lua 5.3, so on Lua 5.1 it failed to load (`records/lua51.txt`).
4.45.0 wrote the same Lua tree.

OpenAPI Generator returns `nil, status, body`, with the status as a string. Its client requires
`http.request` when it loads, and its [generator page](https://openapi-generator.tech/docs/generators/lua/)
marks BearerToken unsupported. So the seam is the module itself: wrap `http.request` in
`package.loaded` before the client loads, as `report.lua` does, or override its templates with
`-t`, as the [templating page](https://openapi-generator.tech/docs/templating/) describes. It
interpolates the id into the path, so real lua-http sent `/v1/items/../shelves`, and
`server.mjs` answered with the shelves. Its `api.mustache` template passes path parameters to
`string.format` as given and query parameters through `encodeURIComponent`, and writes headers for
API key, basic and OAuth schemes only. 7.27.0 is the newest release on Maven Central.

`swift-openapi-generator` writes Swift only, so it has no Lua target. Its runtime's
[`ClientTransport`](https://swiftpackageindex.com/apple/swift-openapi-runtime/1.13.4/documentation/openapiruntime/clienttransport)
decouples the HTTP library from generated code, which is this page's transport function in Swift,
except that its `send` throws where this page returns `nil, err`. For a Lua SDK it is a design to
copy and nothing more.

## Check it worked

```bash
lua5.4 test.lua
```

```text output
ok   the stand-in run of luasocket matches the real one on Lua 5.4
ok   the stand-in run of luasocket matches the real one on Lua 5.1
ok   the stand-in run of luahttp matches the real one on Lua 5.1
ok   the records: busted, Lua 5.1, the rockspecs, and the newest sdkgen
23 tests, 23 passed, 0 failed
```

One test makes a failing call inside `pcall` and expects `ok` to be true, so a raise fails it.
Two more feed the SDK arguments of the wrong type and transports of their own: one that fails
mid-body, one with a table for a body, and one that raises. Each checks the error's fields. Another
checks that every phase outside the cosocket list returns `nil, err` with no connection made.

## When it goes wrong

The client is built in `init_by_lua_block` with a transport that opens its connection as it is
built, so it calls `ngx.socket.tcp` in the `init` phase, where lua-nginx-module disables
cosockets. Build the client there if you like, and open the connection per request, as
`pitfall.lua` shows on the stand-in.

```bash
lua5.4 pitfall.lua
```

```text output
pantry.transport.resty
  init: build the client             built (connections made: 0)
  init: list_items()                 nil, pantry: transport: resty: cosockets are not available in the init phase (connections made: 0)
  content: list_items()              3 items (connections made: 1)
  content: list_items() again        3 items (connections made: 2)
a transport that connects when it is built
  init: build the client             raised: stand-in resty.http: no cosockets in the init phase (connections made: 0)
```

A call needed at start-up goes in a zero-delay `ngx.timer.at` created in
`init_worker_by_lua_block`, the workaround lua-nginx-module documents when the caller need not wait
for the answer. The timer phase allows cosockets, and
[`ngx.timer.at`](https://github.com/openresty/lua-nginx-module#ngxtimerat) is not available in
`init_by_lua*`.

`list_items()` on the OpenAPI Generator client raises inside `http.util.encodeURIComponent`,
because an optional query parameter left `nil` reaches it. Pass every optional argument, or wrap
the call in `pcall`.

A refused connection reaches an sdkgen caller with `err.code` empty when `system.fetch` returns
the transport's error as a string. Return `PantryError.new("transport", message)` from the
adapter, as `generated.lua` does, and branch on the code.

## When not to do this

Do not write a transport contract for one runtime. A script that only ever runs under plain Lua
needs LuaSocket called directly, and the seam is code nobody swaps.

Do not take the sdkgen Lua target for OpenResty. It needs Lua 5.3 or later, which LuaJIT is not,
and its rockspec failed `luarocks lint` twice, on its filename and then on `issues_url`. Take it
when the API owner already publishes sdkgen SDKs and your Lua is 5.3 or later.

Generate a quick client for plain Lua with OpenAPI Generator when lua-http is installed, and wrap
`http.request` for the token and escape ids yourself. `swift-openapi-generator`
earns its place when the same team also ships a Swift client, and its transport protocol is the
model to copy.

## Related how-tos

- [Design an SDK constructor that takes configuration once](/howto/sdk-client-constructor-and-configuration)

- [Paginate an API with Lua coroutines](/howto/paginate-an-api-with-lua-coroutines)

- [Write a new language generator for a Lua SDK](/howto/write-a-new-language-generator-for-lua)

- [Build a PHP SDK that takes any PSR-18 HTTP client](/howto/php-sdk-on-psr-18-http-clients)

## Last verified

Verified 2026-11-22 against Lua 5.4.6 and 5.1.5, with LuaSocket 3.1.0, lua-http 0.4, busted 2.2.0 and
luarocks 3.8.0 from Ubuntu's packages. The generators were OpenAPI Generator 7.27.0,
@voxgig/create-sdkgen 0.31.9, @voxgig/sdkgen 4.44.3 and 4.45.0, and @voxgig/apidef 8.32.4, with
`dkjson` 2.8 and `basexx` 0.4.1, vendored unmodified under `lib/` with their MIT licenses. Every
output block is what the
command preceding it printed, on the stand-ins. The real libraries ran once, in `record.sh`.
OpenResty was not run: the OpenResty transport was tested against a stand-in written from
lua-resty-http's README and lua-nginx-module's phase lists. `swift-openapi-generator` was read
from its documentation, not run.

[^1]: The section of [Programming in Lua](https://www.lua.org/pil/8.3.html) that sets the rule
opens with a Latin proverb about human error, and the edition online is the first, written for Lua 5.0. Its
two examples are `math.sin` called on a table, which raises, and `io.open` on a missing file, which
returns `nil` and a message. An HTTP request is the second kind, because no caller can check that
a server will answer before asking it.

[^2]: The [lua-nginx-module README](https://github.com/openresty/lua-nginx-module#cosockets-not-available-everywhere)
blames the missing cosockets in `set`, `log`, `header_filter` and `body_filter` on internal
limitations in the nginx core. For `init_by_lua*` and `init_worker_by_lua*` it says there is no
such limitation, and that support may be added. Its section on `init_by_lua` adds that Lua
libraries that block are safe there, because blocking the master process during server
start-up is, in its words, completely okay.