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.
You will need
Section titled “You will need”- apic installed (lesson 1)
apic demorunning in another terminal, or start it now:
apic demo --out apic-demojq, for the checkpoint. Every other step is apic alone.
1. Start from an OpenAPI document
Section titled “1. Start from an OpenAPI document”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):
cat > todos-openapi.yaml <<'EOF'openapi: 3.0.3info: { title: Todos, version: "1.0" }servers: - url: http://localhost:8089paths: /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 }EOFImport it into a new directory:
apic import todos-openapi.yaml -o todos-apiwrote todos-api/api.httpwrote todos-api/todos.httpwrote todos-api/http-client.env.json (baseUrl = http://localhost:8089)4 request(s) generated; run `apic list` to see themOne 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:
cat todos-api/todos.http# Tag "todos" — generated by `apic import` from "todos-openapi.yaml". Edit freely.
### List todos# @name list-todos# @assert status == 200GET {{baseUrl}}/todos # ?done={{done}} (optional)Accept: application/json
### Create a todo# @name create-todo# @assert status == 201POST {{baseUrl}}/todosContent-Type: application/jsonAccept: application/json
{ "title": "Buy milk", "done": false}
### Fetch one todo# @name get-todo# @assert status == 200GET {{baseUrl}}/todos/{{todoId}}Accept: application/jsonEverything 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:
apic validate -C todos-apiapic list -C todos-api✓ 2 files, 4 requests, no problemsID METHOD URL LINE DESCRIPTIONapi.httphealth GET {{baseUrl}}/health :6 GET /healthtodos.httplist-todos GET {{baseUrl}}/todos :6 List todoscreate-todo POST {{baseUrl}}/todos :13 Create a todoget-todo GET {{baseUrl}}/todos/{{todoId}} :25 Fetch one todo
4 requests in 2 files · apic describe <id> · apic run <id> · apic uiValid, but not yet runnable. Try the health check:
apic run health -C todos-api || echo "exit $?"GET {{baseUrl}}/healtherror: 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/#e101exit 2The 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:
printf 'env: dev\n' > todos-api/apic.yamlapic run health -C todos-apiGET http://localhost:8089/health200 OK · 0 ms · 74 B
{ "service": "apic-demo", "status": "ok", "uptime_seconds": 89, "version": "v0.2.0"}
✓ status == 2003. 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:
apic mock todos-openapi.yaml --port 8090 > mock.log 2>&1 < /dev/null &echo $! > mock.pidsleep 1cat mock.logmock api listening on http://localhost:8090 · 4 routes from todos-openapi.yaml GET /todos 200 POST /todos 201 GET /todos/{todoId} 200 GET /health 200try: apic run <request> --var baseUrl=http://localhost:8090The 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:
apic run list-todos -C todos-api --var baseUrl=http://localhost:8090GET http://localhost:8090/todos200 OK · 0 ms · 70 B
[ { "id": "1", "title": "Buy milk", "done": false }]
✓ status == 200That 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:
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/999Prefer: code=404EOFapic run missing-todo -C todos-api --var baseUrl=http://localhost:8090GET http://localhost:8090/todos/999404 Not Found · 0 ms · 27 B
{ "error": "not found"}
✓ status == 404✓ body.$.error == not foundBe 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:
kill "$(cat mock.pid)"4. Tidy the draft until it runs green
Section titled “4. Tidy the draft until it runs green”Now the todos, against the demo again:
apic run list-todos -C todos-api || echo "exit $?"GET http://localhost:8089/todos401 Unauthorized · 0 ms · 28 B
{ "error": "unauthenticated"}
✗ status == 200 (actual: 401)exit 1The 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:
cat > todos-api/auth.http <<'EOF'### Log in and keep the token# @name login# @assert status == 200# @capture token = body.$.access_tokenPOST {{baseUrl}}/auth/loginContent-Type: application/json
{"user": "alice", "password": "s3cret"}EOFThen 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:
cat > todos-api/todos.http <<'EOF'### List todos# @name list-todos# @ref login# @auth bearer {{token}}# @assert status == 200GET {{baseUrl}}/todos
### Create a todo# @name create-todo# @ref login# @auth bearer {{token}}# @assert status == 201# @capture todoId = body.$.idPOST {{baseUrl}}/todosContent-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}}EOFThe file is now a flow, in the sense of lesson 3: list, create, fetch what was created. Run it:
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 msWithout 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.
5. From a Postman collection
Section titled “5. From a Postman collection”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:
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"}]}}} ]} ]}EOFcat > local.postman_environment.json <<'EOF'{"name": "local", "values": [ {"key": "user", "value": "alice", "enabled": true}, {"key": "password", "value": "s3cret", "type": "secret", "enabled": true}]}EOFapic import todos.postman_collection.json -o postman-api --postman-env local.postman_environment.jsonwrote postman-api/auth.httpwrote postman-api/todos.httpwrote postman-api/http-client.private.env.jsonwrote postman-api/apic.yamlwrote postman-api/http-client.env.json (baseUrl = http://localhost:8089)3 request(s) generated; run `apic list` to see themnote log-in: console.log("done");: test script line not translated; apic has no scriptingFolders 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:
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 == 200POST {{baseUrl}}/auth/loginContent-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:
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 ms6. From a curl command
Section titled “6. From a curl command”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:
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-apitail -8 todos-api/todos.httpadded finish-todo to todos.http
### PUT /todos/1# @name finish-todo# @assert status == 200PUT {{baseUrl}}/todos/1Authorization: Bearer mock-tokenContent-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:
apic run finish-todo -C todos-api | tail -1✓ status == 200But 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.
7. Back to curl
Section titled “7. Back to curl”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:
apic curl get-todo -C todos-apicurl -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:
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:
apic curl get-todo -C todos-api --redactcurl -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:
apic snippet get-todo -C todos-api --lang python --redactimport 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)Checkpoint
Section titled “Checkpoint”The imported project runs green as a flow, login included:
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.)
Exercise
Section titled “Exercise”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
curl -fsSL https://petstore3.swagger.io/api/v3/openapi.json -o petstore.jsonapic import petstore.json -o petstoreprintf 'env: dev\n' > petstore/apic.yamlapic list -C petstore | grep inventoryapic run get-inventory -C petstoreThe 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.
Going further
Section titled “Going further”apic import, every mapping for OpenAPI, Postman and curl, and what each importer reports as unsupportedapic mock, how a response is chosen and built, thePreferheader, and what the mock deliberately does not doapic curland 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.
- The OpenAPI import: what the spec knew, what it did not.
- Validate and list on a draft; the missing environment and the
one-line
apic.yaml. apic mock: the document as the server,--var baseUrlto point one run at it,Prefer: code=404for the error path, and what it proves (the requests match the contract) and does not (anything about the API).- 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.” - The Postman collection: folders to files, the environment and its
secret, test scripts to directives, the
notelines for what could not be translated. - The curl import with
--into, and the literal token it carries. apic curl,| sh, and--redactfor a bug report.- 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