Skip to content

Lesson 9: From OpenAPI to a project, and back to curl

Goal. Turn an OpenAPI document, a Postman collection or a curl command into a project, run the draft against a mock of the document before any API exists, tidy it into something that runs green, and get a curl command back out for the machine that has no apic.

  • apic installed (lesson 1)
  • apic demo running in another terminal, or start it now:
Terminal window
apic demo --out apic-demo
  • jq, for the checkpoint. Every other step is apic alone.

Most projects do not start from an empty directory: there is a spec, a collection or a pile of curl commands in a wiki. apic’s importers turn each into a first draft of .http files, and a draft is all they are: the work of this lesson is turning one into something runnable.

The demo API has no published spec, so write a small one for its todos. Three operations under a todos tag, one untagged health check, and schemas with examples for what goes in and what comes back (the responses matter in step 3, when the document itself is the server):

Terminal window
cat > todos-openapi.yaml <<'EOF'
openapi: 3.0.3
info: { title: Todos, version: "1.0" }
servers:
- url: http://localhost:8089
paths:
/todos:
get:
tags: [todos]
operationId: listTodos
summary: List todos
parameters:
- name: done
in: query
schema: { type: boolean }
responses:
"200":
description: ok
content:
application/json:
schema: { type: array, items: { $ref: "#/components/schemas/Todo" } }
post:
tags: [todos]
operationId: createTodo
summary: Create a todo
requestBody:
required: true
content:
application/json:
schema: { $ref: "#/components/schemas/NewTodo" }
responses:
"201":
description: created
content:
application/json:
schema: { $ref: "#/components/schemas/Todo" }
/todos/{todoId}:
get:
tags: [todos]
operationId: getTodo
summary: Fetch one todo
parameters:
- name: todoId
in: path
required: true
schema: { type: string }
responses:
"200":
description: ok
content:
application/json:
schema: { $ref: "#/components/schemas/Todo" }
"404":
description: no such todo
content:
application/json:
example: { error: not found }
/health:
get:
operationId: health
responses:
"200": { description: ok }
components:
schemas:
NewTodo:
type: object
required: [title]
properties:
title: { type: string, example: Buy milk }
done: { type: boolean, default: false }
Todo:
type: object
properties:
id: { type: string, example: "1" }
title: { type: string, example: Buy milk }
done: { type: boolean, default: false }
EOF

Import it into a new directory:

Terminal window
apic import todos-openapi.yaml -o todos-api
wrote todos-api/api.http
wrote todos-api/todos.http
wrote todos-api/http-client.env.json (baseUrl = http://localhost:8089)
4 request(s) generated; run `apic list` to see them

One file per tag, operations without a tag in api.http, and an env file with baseUrl from the first server. Look at the tagged file:

Terminal window
cat todos-api/todos.http
# Tag "todos" — generated by `apic import` from "todos-openapi.yaml". Edit freely.
### List todos
# @name list-todos
# @assert status == 200
GET {{baseUrl}}/todos
# ?done={{done}} (optional)
Accept: application/json
### Create a todo
# @name create-todo
# @assert status == 201
POST {{baseUrl}}/todos
Content-Type: application/json
Accept: application/json
{
"title": "Buy milk",
"done": false
}
### Fetch one todo
# @name get-todo
# @assert status == 200
GET {{baseUrl}}/todos/{{todoId}}
Accept: application/json

Everything the spec knew is there: the operationId in kebab-case as the name, the summary as the title, the first 2xx code as an assertion, the optional query parameter as a commented line to uncomment, the path parameter as {{todoId}}, an Accept header because the responses are JSON, and a body built from the schema with its example and its default. What the spec did not know is the interesting part, and steps 2 and 4 find it.

2. Check the draft before sending anything

Section titled “2. Check the draft before sending anything”

validate and list work on a draft exactly as on a finished project:

Terminal window
apic validate -C todos-api
apic list -C todos-api
✓ 2 files, 4 requests, no problems
ID METHOD URL LINE DESCRIPTION
api.http
health GET {{baseUrl}}/health :6 GET /health
todos.http
list-todos GET {{baseUrl}}/todos :6 List todos
create-todo POST {{baseUrl}}/todos :13 Create a todo
get-todo GET {{baseUrl}}/todos/{{todoId}} :25 Fetch one todo
4 requests in 2 files · apic describe <id> · apic run <id> · apic ui

Valid, but not yet runnable. Try the health check:

Terminal window
apic run health -C todos-api || echo "exit $?"
GET {{baseUrl}}/health
error: api.http:6: missing variable
{{baseUrl}}: pass --var baseUrl=... or add it to http-client.env.json
hint: Pass it with --var name=value, add it to an env file, or run the request that captures it first.
E101 missing variable · see https://apic.sh/errors/#e101
exit 2

The value is in http-client.env.json, under an environment called dev (the importer’s default; --env-name picks another), but nothing selects that environment yet. --env dev on every command would work; the permanent fix is the one-line apic.yaml from lesson 2:

Terminal window
printf 'env: dev\n' > todos-api/apic.yaml
apic run health -C todos-api
GET http://localhost:8089/health
200 OK · 0 ms · 74 B
{
"service": "apic-demo",
"status": "ok",
"uptime_seconds": 89,
"version": "v0.2.0"
}
✓ status == 200

3. Run the draft against the document itself

Section titled “3. Run the draft against the document itself”

This lesson has been lucky so far: the demo API is running. On a real project the document often arrives before the backend, and a draft with nothing to send to is hard to judge. apic mock serves the document itself: every operation answers with the response it declares, its example or a value built from its schema. Start it in the background, on a port of its own, and keep its process id so you can stop it later:

Terminal window
apic mock todos-openapi.yaml --port 8090 > mock.log 2>&1 < /dev/null &
echo $! > mock.pid
sleep 1
cat mock.log
mock api listening on http://localhost:8090 · 4 routes from todos-openapi.yaml
GET /todos 200
POST /todos 201
GET /todos/{todoId} 200
GET /health 200
try: apic run <request> --var baseUrl=http://localhost:8090

The env file still points at the demo on 8089, and a --var on the command line wins over it (lesson 2), so pointing one run at the mock is one flag:

Terminal window
apic run list-todos -C todos-api --var baseUrl=http://localhost:8090
GET http://localhost:8090/todos
200 OK · 0 ms · 70 B
[
{
"id": "1",
"title": "Buy milk",
"done": false
}
]
✓ status == 200

That is the Todo schema read back: one element, the examples and the default filled in. The document also promised a 404 for a todo that does not exist, and the mock serves any documented response on request: a Prefer: code=404 header line asks for that one. Put the error path in a file of its own, with the assertions the document lets you make:

Terminal window
cat > todos-api/contract.http <<'EOF'
### A todo that does not exist
# @name missing-todo
# @assert status == 404
# @assert body.$.error == "not found"
GET {{baseUrl}}/todos/999
Prefer: code=404
EOF
Terminal window
apic run missing-todo -C todos-api --var baseUrl=http://localhost:8090
GET http://localhost:8090/todos/999
404 Not Found · 0 ms · 27 B
{
"error": "not found"
}
✓ status == 404
✓ body.$.error == not found

Be clear about what this proves. The requests and the document agree: the paths, the methods, the shapes and the status codes match, and the assertions you wrote are ones the contract supports. It proves nothing about the API, because there is none yet, and the mock keeps no state: a create-todo against it answers with the schema’s example, and a get-todo after it knows nothing about what was created. When the backend exists, the env file takes you there and the same files run against it. Here the backend is the demo, so stop the mock:

Terminal window
kill "$(cat mock.pid)"

Now the todos, against the demo again:

Terminal window
apic run list-todos -C todos-api || echo "exit $?"
GET http://localhost:8089/todos
401 Unauthorized · 0 ms · 28 B
{
"error": "unauthenticated"
}
✗ status == 200 (actual: 401)
exit 1

The spec never mentioned authentication, which is common: security schemes are the part of an OpenAPI document most often left out or left vague. This is the tidy-up every import needs, and it is the same four directives the course has used since lessons 3 and 6. (It is also why contract.http from step 3 cannot run against the demo as it stands: the mock asked for no token because the document named none.) Add a login request that captures the token:

Terminal window
cat > todos-api/auth.http <<'EOF'
### Log in and keep the token
# @name login
# @assert status == 200
# @capture token = body.$.access_token
POST {{baseUrl}}/auth/login
Content-Type: application/json
{"user": "alice", "password": "s3cret"}
EOF

Then give each todo request # @ref login so the token is fetched when it is missing, # @auth bearer {{token}} to send it, and make create-todo capture the id that get-todo needs:

Terminal window
cat > todos-api/todos.http <<'EOF'
### List todos
# @name list-todos
# @ref login
# @auth bearer {{token}}
# @assert status == 200
GET {{baseUrl}}/todos
### Create a todo
# @name create-todo
# @ref login
# @auth bearer {{token}}
# @assert status == 201
# @capture todoId = body.$.id
POST {{baseUrl}}/todos
Content-Type: application/json
{
"title": "Buy milk",
"done": false
}
### Fetch one todo
# @name get-todo
# @ref login
# @auth bearer {{token}}
# @assert status == 200
# @assert body.$.title == "Buy milk"
GET {{baseUrl}}/todos/{{todoId}}
EOF

The file is now a flow, in the sense of lesson 3: list, create, fetch what was created. Run it:

Terminal window
apic run todos.http -C todos-api | tail -5
✓ list-todos 200 0 ms
✓ create-todo 201 0 ms
✓ get-todo 200 0 ms
3 passed · 3 requests · 0 ms

Without tail you would also see ↳ ran login first (# @ref) once, above list-todos: the three requests all declare the dependency, and it ran once. That is the whole method for any import: generate, run, and add the directive that the failure asks for, until the file is green.

A Postman export is a JSON file; apic import recognises it by its content. Write a small collection with the same two things a real one has, a test script and a folder with its own auth, and an environment export with a secret in it:

Terminal window
cat > todos.postman_collection.json <<'EOF'
{
"info": {"name": "Todos", "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"},
"variable": [{"key": "baseUrl", "value": "http://localhost:8089"}],
"item": [
{"name": "Auth", "item": [
{"name": "Log in",
"request": {"method": "POST", "url": "{{baseUrl}}/auth/login",
"header": [{"key": "Content-Type", "value": "application/json"}],
"body": {"mode": "raw", "raw": "{\"user\": \"{{user}}\", \"password\": \"{{password}}\"}", "options": {"raw": {"language": "json"}}}},
"event": [{"listen": "test", "script": {"exec": [
"pm.test(\"logged in\", function () {",
" pm.response.to.have.status(200);",
" pm.environment.set(\"token\", pm.response.json().access_token);",
"});",
"console.log(\"done\");"
]}}]}
]},
{"name": "Todos", "auth": {"type": "bearer", "bearer": [{"key": "token", "value": "{{token}}"}]}, "item": [
{"name": "List todos", "request": {"method": "GET", "url": "{{baseUrl}}/todos?done=false"}},
{"name": "Get todo", "request": {"method": "GET", "url": {"raw": "{{baseUrl}}/todos/:id", "variable": [{"key": "id", "value": "1"}]}}}
]}
]
}
EOF
cat > local.postman_environment.json <<'EOF'
{"name": "local", "values": [
{"key": "user", "value": "alice", "enabled": true},
{"key": "password", "value": "s3cret", "type": "secret", "enabled": true}
]}
EOF
apic import todos.postman_collection.json -o postman-api --postman-env local.postman_environment.json
wrote postman-api/auth.http
wrote postman-api/todos.http
wrote postman-api/http-client.private.env.json
wrote postman-api/apic.yaml
wrote postman-api/http-client.env.json (baseUrl = http://localhost:8089)
3 request(s) generated; run `apic list` to see them
note log-in: console.log("done");: test script line not translated; apic has no scripting

Folders became files, the collection variable became $shared, the environment became local with its secret in the private file (written 0600) and selected in apic.yaml. The test script became directives:

Terminal window
cat postman-api/auth.http
# auth — generated by `apic import` from "todos.postman_collection.json". Edit freely.
### Log in
# @name log-in
# @capture token = body.$.access_token
# @assert status == 200
POST {{baseUrl}}/auth/login
Content-Type: application/json
{"user": "{{user}}", "password": "{{password}}"}

pm.response.to.have.status(200) is # @assert status == 200, pm.environment.set("token", …) is # @capture token = …. The console.log line has no equivalent and the importer said so rather than dropping it silently; every line it cannot translate is listed the same way, so you know exactly what to re-create by hand. The folder’s bearer auth became # @auth bearer {{token}} on both todo requests, and the draft runs as it is:

Terminal window
apic run log-in list-todos -C postman-api | tail -4
✓ log-in 200 0 ms
✓ list-todos 200 0 ms
2 passed · 2 requests · 0 ms

The third source is the curl command in a README or a bug report. --curl turns one into a block, and --into appends it to a file of the project:

Terminal window
apic import --curl 'curl -X PUT http://localhost:8089/todos/1 -H "Authorization: Bearer mock-token" -H "Content-Type: application/json" -d '"'"'{"done":true}'"'"'' \
--into todos.http --name finish-todo -C todos-api
tail -8 todos-api/todos.http
added finish-todo to todos.http
### PUT /todos/1
# @name finish-todo
# @assert status == 200
PUT {{baseUrl}}/todos/1
Authorization: Bearer mock-token
Content-Type: application/json
{"done":true}

The host became {{baseUrl}} because the project’s environment has that value; the headers and body came across as written. It runs:

Terminal window
apic run finish-todo -C todos-api | tail -1
✓ status == 200

But look at what it carries: a literal token, the way the curl command did. The tidy-up is the same as in step 4: replace the Authorization line with # @auth bearer {{token}} and # @ref login, and /todos/1 with /todos/{{todoId}}. An import gives you the shape; the directives give you the project.

The way out is apic curl: the request with every variable resolved, as a shell command, for a machine that has curl and nothing else, or for a bug report:

Terminal window
apic curl get-todo -C todos-api
curl -sS \
-H 'Authorization: Bearer mock-token' \
'http://localhost:8089/todos/3'

The token and the id came from the session, so it is the request as apic would send it now (a fresh demo seeds two todos, so the one the flow created is 3; yours is higher if you created more). Pipe it into a shell and it runs:

Terminal window
apic curl get-todo -C todos-api | sh
{"id":"3","title":"Buy milk","done":false}

For a bug report or a stored log, --redact keeps the shape and masks the values, with the credential as a shell variable so the reader can still run it with their own:

Terminal window
apic curl get-todo -C todos-api --redact
curl -sS \
-H "Authorization: Bearer $TOKEN" \
'http://localhost:8089/todos/3'

curl is one language of six. apic snippet prints the same request as HTTPie, PowerShell, Python, JavaScript or Go, with the same rules for secrets, for the colleague on Windows or the service’s README:

Terminal window
apic snippet get-todo -C todos-api --lang python --redact
import os
import requests
response = requests.request(
"GET",
"http://localhost:8089/todos/3",
headers={
"Authorization": "Bearer " + os.environ["TOKEN"],
},
)
print(response.status_code)
print(response.text)

The imported project runs green as a flow, login included:

Terminal window
apic run todos.http -C todos-api --json | jq -s 'map(.ok) | all'
true

(Without jq: apic run todos.http -C todos-api --json | grep -c '"ok":true' prints 4, one per request in the file, finish-todo from step 6 included.)

Import a public OpenAPI document of your choice and get one request green. The Swagger Petstore publishes its document at https://petstore3.swagger.io/api/v3/openapi.json, and its GET /store/inventory needs no account.

Solution
Terminal window
curl -fsSL https://petstore3.swagger.io/api/v3/openapi.json -o petstore.json
apic import petstore.json -o petstore
printf 'env: dev\n' > petstore/apic.yaml
apic list -C petstore | grep inventory
apic run get-inventory -C petstore

The importer names the request from its operationId (getInventory); apic list shows every id if the name differs. The apic.yaml line is the same fix as step 2, and the first thing to add after that is usually # @auth, as in step 4. Pick a second request that needs a path parameter and give it a {{variable}} from a capture on the first.

  • apic import, every mapping for OpenAPI, Postman and curl, and what each importer reports as unsupported
  • apic mock, how a response is chosen and built, the Prefer header, and what the mock deliberately does not do
  • apic curl and the auth mapping onto curl’s own flags
  • Comparison with Postman, Bruno, Hurl and httpyac, including what apic does instead of scripting
Episode script

Length. 12 minutes.

Cold open (0:00). A README with six curl commands and a Postman collection with test scripts nobody has run in a year. “You do not start from zero. Here is how you start from what you have.”

Talking points.

  1. The OpenAPI import: what the spec knew, what it did not.
  2. Validate and list on a draft; the missing environment and the one-line apic.yaml.
  3. apic mock: the document as the server, --var baseUrl to point one run at it, Prefer: code=404 for the error path, and what it proves (the requests match the contract) and does not (anything about the API).
  4. The 401 and the tidy-up: login, # @ref, # @auth, # @capture, and the file running as a flow. “Generate, run, add the directive the failure asks for.”
  5. The Postman collection: folders to files, the environment and its secret, test scripts to directives, the note lines for what could not be translated.
  6. The curl import with --into, and the literal token it carries.
  7. apic curl, | sh, and --redact for a bug report.
  8. Checkpoint, then the petstore exercise.

Shot list. One terminal, 100x30, font size 16, the docs theme. docs/learn/tapes/09.tape drives it. Zoom on the note line of the Postman import and on the literal token in the curl block.

Chapters. 0:00 What you already have · 0:40 Import an OpenAPI document · 2:30 Validate, list, the missing env · 3:40 The tidy-up · 5:30 A Postman collection · 7:10 A curl command · 8:10 Back to curl · 9:00 Checkpoint and exercise.

Description. From the episode template.

Hosted on Cloudflare, which keeps aggregate traffic statistics. No cookies, no tracking scripts, no per-request logs. Privacy