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, tidy the draft into something that runs green, and get a curl command back out for the machine that has no apic.

You will need

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

Steps

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 a schema with an example:

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 }
    post:
      tags: [todos]
      operationId: createTodo
      summary: Create a todo
      requestBody:
        required: true
        content:
          application/json:
            schema: { $ref: "#/components/schemas/NewTodo" }
      responses:
        "201": { description: created }
  /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 }
  /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 }
EOF

Import it into a new directory:

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:

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)

### Create a todo
# @name create-todo
# @assert status == 201
POST {{baseUrl}}/todos
Content-Type: application/json

{
  "title": "Buy milk",
  "done": false
}

### Fetch one todo
# @name get-todo
# @assert status == 200
GET {{baseUrl}}/todos/{{todoId}}

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}}, and a body built from the schema with its example and its default. What the spec did not know is the interesting part, and the next two steps find it.

2. Check the draft before sending anything

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

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             :12   Create a todo
get-todo     GET     {{baseUrl}}/todos/{{todoId}}  :23   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:

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

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": "dev"
}

✓ status == 200

3. Tidy the draft until it runs green

Now the todos:

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 lesson 3. 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_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:

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:

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.

4. 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"}]}}}
    ]}
  ]
}
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:

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:

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

5. 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-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:

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 3: 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.

6. 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-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:

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

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)

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, the login that # @ref ran and the three requests.)

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.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 3. Pick a second request that needs a path parameter and give it a {{variable}} from a capture on the first.

Going further

  • apic import, every mapping for OpenAPI, Postman and curl, and what each importer reports as unsupported
  • 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. 10 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. 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."
  4. The Postman collection: folders to files, the environment and its secret, test scripts to directives, the note lines for what could not be translated.
  5. The curl import with --into, and the literal token it carries.
  6. apic curl, | sh, and --redact for a bug report.
  7. 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.