# apic > apic is epic: run API requests from plain .http files, in the terminal, in CI, or from an AI agent, on any platform, with one static binary. Every page of apic.sh, the documentation for the apic CLI, in one document, in the sidebar's order. The short index is at https://apic.sh/llms.txt. --- # apic is epic URL: https://apic.sh/ Run API requests from plain .http files, in the terminal, in CI, or from an AI agent, on any platform, with one static binary. ![apic ui --demo: send a request, run a file as a flow, read the checks, see what was captured](assets/apic-demo.svg) ```sh wrap apic ui --demo # a fake API and a UI on it, no setup apic run login # POST, capture the token apic run get-user --env staging # reuse the token, check assertions apic run smoke.http --json | jq # a file as a flow, one JSON line each apic test # Gherkin features, same requests claude mcp add api -- apic mcp # an agent calls them as tools ``` ## 30 seconds to epic **Homebrew:** ```sh brew install hungovercoders/tap/apic apic ui --demo ``` **Go:** ```sh go install github.com/hungovercoders/apic/cmd/apic@latest apic ui --demo ``` **Linux / macOS:** ```sh curl -fsSL https://raw.githubusercontent.com/hungovercoders/apic/main/install.sh | sh apic ui --demo ``` **Windows:** ```powershell irm https://raw.githubusercontent.com/hungovercoders/apic/main/install.ps1 | iex apic ui --demo ``` `--demo` serves a small fake API inside the same process and opens the [terminal UI](https://apic.sh/tui/) on an example project that targets it. There is nothing to sign up for or clone, and nothing is left behind when you quit. :::tip[Prefer the plain CLI?] `apic demo` writes the same example project to `./apic-demo` and serves the API, so you can drive it by hand: `apic run login whoami -C apic-demo`. ::: ## Why it's epic - [Environments that travel](https://apic.sh/format/#variables): http-client.env.json, .env, the shell and --var, with one precedence order you can print. - [Tokens that persist](https://apic.sh/format/#directives): Capture a value once; the next run, in a new shell or a new agent call, already has it. - [Assertions and flows](https://apic.sh/format/#assertion-operators): Check status, headers and JSON paths. A file runs in order with a pass/fail summary and an exit code. - [Auth a text file cannot do](https://apic.sh/auth/): AWS SigV4 with no SDK, OAuth2 with caching and refresh, basic, bearer, or any CLI that prints a token. - [Gherkin without Cucumber](https://apic.sh/testing/): Features run against the same requests with a built-in vocabulary. JUnit and cucumber reports included. - [Built for agents](https://apic.sh/agents/): Stable --json per request, discoverable requests, errors that say what to do next, and an MCP server. The files stay ordinary `.http` files: everything apic adds is a comment, so VS Code, JetBrains and Neovim still send them with one click. ## Where to go next - [Getting started](https://apic.sh/getting-started/): set apic up for a project. - [From zero to apic](https://apic.sh/learn/): the course, fourteen short lessons. - [Cheat sheet](https://apic.sh/cheatsheet/): every directive, selector and operator on one page. - [The `.http` format](https://apic.sh/format/): the files you are writing. - [Using apic from an AI agent](https://apic.sh/agents/): the contract for Claude Code, Cursor or a shell-driven agent. The sidebar and search carry the rest. :::note[Reading this as an agent?] [llms.txt](https://apic.sh/llms.txt) maps every page with a summary, and [llms-full.txt](https://apic.sh/llms-full.txt) is the whole site as one Markdown document. [Using apic from an AI agent](https://apic.sh/agents/) is the contract. ::: --- # Getting started URL: https://apic.sh/getting-started/ Install apic, describe an API in .http files, log in once and reuse the token, wire it into CI and hand the same files to an AI agent, in about ten minutes. This walks through installing apic, describing an API in `.http` files, logging in once and reusing the token, wiring it into CI, and handing the same files to an AI agent. It takes about ten minutes. ## 1. Install **Homebrew:** ```sh brew install hungovercoders/tap/apic ``` macOS and Linux. The tap is [hungovercoders/homebrew-tap](https://github.com/hungovercoders/homebrew-tap); the cask installs the binary, the man pages and shell completions, and `brew upgrade` follows releases. **Go:** ```sh go install github.com/hungovercoders/apic/cmd/apic@latest # Go 1.25.7 or newer ``` **Linux / macOS:** Without Homebrew: ```sh curl -fsSL https://raw.githubusercontent.com/hungovercoders/apic/main/install.sh | sh ``` `| APIC_VERSION=v1.2.3 sh` pins a version, `| APIC_INSTALL_DIR=~/bin sh` chooses where it lands; the variable goes before `sh`, which runs the installer. The installer verifies the release checksum. **deb, rpm, apk:** Each release has packages for Debian and Ubuntu, Fedora and RHEL, and Alpine, for amd64 and arm64, with the man pages and shell completions: ```sh V=0.2.0 # the release, without the v A=amd64 # or arm64 BASE=https://github.com/hungovercoders/apic/releases/download/v$V curl -fsSLO "$BASE/apic_${V}_linux_${A}.deb" && sudo dpkg -i "apic_${V}_linux_${A}.deb" # Debian, Ubuntu curl -fsSLO "$BASE/apic_${V}_linux_${A}.rpm" && sudo rpm -i "apic_${V}_linux_${A}.rpm" # Fedora, RHEL curl -fsSLO "$BASE/apic_${V}_linux_${A}.apk" && apk add --allow-untrusted "apic_${V}_linux_${A}.apk" # Alpine ``` There is no apt, yum or apk repository, so upgrading means installing the next release's package. The packages are listed in `checksums.txt` with the archives; [verifying.md](https://apic.sh/verifying/) checks them the same way. The apk is unsigned, hence `--allow-untrusted`: check its checksum first. **Windows:** ```powershell irm https://raw.githubusercontent.com/hungovercoders/apic/main/install.ps1 | iex ``` It installs `apic.exe` into `%LOCALAPPDATA%\Programs\apic`, verifies the release checksum, and adds the directory to your user `PATH`. `$env:APIC_VERSION = "v1.2.3"` pins a version, `$env:APIC_INSTALL_DIR` chooses the directory and `$env:APIC_NO_MODIFY_PATH = "1"` leaves `PATH` alone. The zip is also on [GitHub Releases](https://github.com/hungovercoders/apic/releases) to install by hand. **Docker:** ```sh docker run --rm -v "$PWD:/work" ghcr.io/hungovercoders/apic version ``` The image is the binary on `scratch`, about 16 MB (about 7 MB to pull), for amd64 and arm64. The project directory is mounted at `/work`; see [the cookbook](https://apic.sh/cookbook/#in-a-container) for CI systems that run containers. Check it with `apic version`. ## 2. See it work before writing anything ```sh apic ui --demo ``` That serves a small fake API inside the same process and opens the [terminal UI](https://apic.sh/tui/) on an example project pointing at it. Press enter to send the request under the cursor, f to run a whole file as a flow, ? for every key, q to quit. Nothing is left behind. The same example works from the plain CLI: `apic demo` writes it to `./apic-demo` and serves the API, then in another terminal: ```sh apic run login whoami -C apic-demo apic run todos.http -C apic-demo --keep-going apic run jobs.http -C apic-demo # submit a job and poll it to done apic test -C apic-demo ``` Read `apic-demo/auth.http`, `todos.http`, `jobs.http` and `explore.http` to see the files behind those commands. Between them they cover login and API keys, a CRUD flow with filtering and a validation error, a job that finishes after a couple of polls, a slow endpoint, a CSV download and a GraphQL query, so every guide in these docs has something to run against. ## 3. Create a project A project is any directory containing `.http` files. Keeping them in an `api/` folder next to your code works well. `apic init` writes a working starting point: ```sh apic init api --base-url https://dev.example.com --env dev ``` ``` api/ apic.yaml http-client.env.json http-client.private.env.json api.http features/smoke.feature .gitignore .claude/skills/apic/ the Agent Skill (--no-skill leaves it out; .agents/skills/apic/ apic skill install --all adds two more) ``` `apic.yaml` sets defaults so you do not repeat flags: ```yaml env: dev ``` `http-client.env.json` holds per-environment values. `$shared` applies to every environment. ```json { "$shared": { "userId": 42 }, "dev": { "baseUrl": "https://dev.example.com", "user": "alice" }, "staging": { "baseUrl": "https://stg.example.com", "user": "alice" } } ``` `http-client.private.env.json` has the same shape and holds secrets. `apic init` gitignores it for you. apic masks values from this file wherever it prints variables. ```json { "dev": { "password": "s3cret" }, "staging": { "password": "other" } } ``` If you already have an OpenAPI document, let apic write the first draft: ```sh apic import openapi.yaml -o api ``` ## 4. Write requests `api/auth.http`: ```http ### 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": "{{user}}", "password": "{{password}}"} ``` `api/users.http`: ```http ### Fetch a user # @name get-user # @description Fetch a single user by id # @assert status == 200 # @assert body.$.id == {{userId}} GET {{baseUrl}}/users/{{userId}} Authorization: Bearer {{token}} Accept: application/json ### Create a user # @name create-user # @assert status == 201 # @capture newUserId = body.$.id POST {{baseUrl}}/users Content-Type: application/json {"name": "{{user}}", "email": "{{user}}@example.com"} ``` These are ordinary `.http` files. Open them in VS Code with the REST Client extension, in a JetBrains IDE, or in Neovim with kulala, and the "Send Request" action works as usual. apic's `# @` lines are comments to those tools. Check the files parse, and see what you have: ```sh cd api apic validate apic list apic list user # only requests matching "user" ``` ## 5. Run requests ```sh apic run get-user ``` The first time, this fails with exit code 2 and tells you why: ``` error: users.http:6: missing variable {{token}}: it is captured by request "login"; run `apic run login` first, or pass --var token=... E101 missing variable · see https://apic.sh/errors/#e101 ``` So log in (or add `# @ref login` to `get-user` and apic does this for you; see [dependencies](https://apic.sh/format/#dependencies)): ```sh apic run login ``` ``` POST https://dev.example.com/auth/login 200 OK · 87 ms · 412 B { "access_token": "eyJ..." } ✓ status == 200 ↳ token = eyJ... ``` The token is now in `api/.apic/session.json` for the `dev` environment (the directory ignores itself from git). Every later run in `dev` can use `{{token}}` until you clear it or log in again: ```sh apic run get-user apic run get-user --env staging # separate session, needs its own login apic describe get-user # see where each variable comes from apic session # what is captured apic session clear # forget it ``` :::tip[Or drive it interactively] `apic ui` shows the same project with the requests on the left and the response, checks and session on the right, and marks which requests are ready to run. See [the terminal UI](https://apic.sh/tui/). ::: Override anything for one run: ```sh apic run get-user --var userId=7 ``` Run a whole file in order as a flow. It stops at the first failure and exits 1 if anything failed: ```sh apic run users.http apic run users.http --keep-going ``` ## 6. Use the output in scripts ```sh apic run get-user --body-only | jq .email apic run users.http --json | jq -c '{name: .request.name, ok, status: .response.status}' ``` Exit codes make apic safe in `set -e` scripts and CI steps: | Code | Meaning | |---|---| | 0 | ok | | 1 | an assertion or capture failed | | 2 | usage, parse error, unknown request or missing variable | | 3 | network error or timeout | ## 7. Put it in CI ```yaml # .github/workflows/smoke.yml - uses: hungovercoders/apic/setup-apic@v0 - run: apic validate -C api --format github - run: apic run auth.http users.http -C api --env staging --json --redact env: APIC_VAR_password: ${{ secrets.API_PASSWORD }} ``` The `setup-apic` action installs the latest release (or `with: version: v0.2.0` to pin one), verifies it against the published checksums, caches it and puts it on `PATH`, on Linux, macOS and Windows runners. On any other CI system, `curl -fsSL https://raw.githubusercontent.com/hungovercoders/apic/main/install.sh | sh` does the same job, and where tools come as images there is [`ghcr.io/hungovercoders/apic`](https://apic.sh/cookbook/#in-a-container). `--format github` turns each validation problem into an annotation on the pull request at the right line. `APIC_VAR_` environment variables override values from the env files, so secrets never need to be in a file on the runner. `--redact` masks header values, bodies, query values and captures in the stored log; sensitive headers are masked even without it. `apic run` runs targets in the order given, so `auth.http users.http` logs in first. ## 8. Add authentication If the API needs more than a bearer token, put it in the file or the project config and apic handles it at send time: ```http # @auth aws service=execute-api region=eu-west-2 # @auth basic {{user}} {{password}} # @auth oauth2 tokenUrl={{tokenUrl}} clientId={{clientId}} clientSecret={{clientSecret}} ``` AWS uses your existing credentials (environment, profiles, SSO via the AWS CLI); OAuth2 tokens are cached and refreshed. See [auth.md](https://apic.sh/auth/). ## 9. Describe behaviour in Gherkin Add phrases to requests and write features; apic runs them with no Cucumber runtime: ```http ### Create a user # @name create-user # @step a user named {name} exists POST {{baseUrl}}/users Content-Type: application/json {"name": "{{name}}", "email": "{{name}}@example.com"} ### Fetch a user # @name get-user # @step I fetch the user GET {{baseUrl}}/users/{{userId}} ``` ```gherkin Feature: Users Scenario: Fetch a user by id Given I run "login" And a user named "alice" exists When I fetch the user Then the response status is 200 And the response body "$.name" is "alice" ``` ```sh apic test # features/ under the project apic test --format junit --output report.xml ``` See [testing.md](https://apic.sh/testing/) for the full vocabulary. ## 10. Hand it to an agent Add to your project's `AGENTS.md` or `CLAUDE.md`: ```markdown API requests live in api/*.http and are run with apic from the api/ directory: `apic list --json`, `apic describe --json`, `apic run --json`. Run `apic run login` once before requests that need {{token}}. ``` Or register the MCP server so the agent calls requests as tools: ```sh claude mcp add api -- apic mcp --dir ./api --env dev ``` See [agents.md](https://apic.sh/agents/) for the details. ## Next - [cheatsheet.md](https://apic.sh/cheatsheet/): every directive, selector and operator on one page - [cookbook.md](https://apic.sh/cookbook/): worked recipes for CI, AWS, OAuth2, uploads and polling - [format.md](https://apic.sh/format/): everything the `.http` dialect supports - [cli.md](https://apic.sh/cli/): every command and flag - [tui.md](https://apic.sh/tui/): the terminal UI - [faq.md](https://apic.sh/faq/): short answers when something misbehaves --- # The terminal UI URL: https://apic.sh/tui/ apic ui, the terminal UI: browse requests, send them, read the response, the checks, the session and the history, with every key and flag explained. `apic ui` is the interactive face of the same project the CLI runs: requests on the left, and a preview, the response, the checks, the session and the history on the right. It sends requests with the same runner as `apic run`, so what you see is what CI will see. ![apic ui](assets/apic-ui.svg) ```sh apic ui # the project in the current directory apic ui -C api --env staging # a project elsewhere, in another environment apic ui --demo # a fake API served in-process, nothing to set up ``` :::note[The one interactive command] Every other apic command is non-interactive and supports `--json`. `apic ui` is the exception: it refuses to start when stdout is not a terminal or when `--json` is given, and tells you to use `apic run` or `apic list` instead. Scripts and agents are never left waiting on a UI. ::: ## Try it with no project `apic ui --demo` writes the bundled example project to a temporary directory, serves the fake API it targets on a free localhost port inside the same process, and opens the UI on it. Quitting shuts the server down and removes the directory. It is the fastest way to see what apic does, and it needs no network access. `apic demo` is the two-terminal version: it writes the same project to `./apic-demo` (in the current directory) and serves the API. Because `apic ui` resolves `.http` files relative to `-C` (default: the current directory), running plain `apic ui` in a second terminal won't see that project — pass `-C apic-demo` (or `cd` into it first). ## Projects are directory-scoped Every apic command, `ui` included, only ever looks at `.http`/`.rest` files under `-C` (default `.`). There is no global registry of projects and no upward search past that directory. If a request doesn't show up, or the UI opens empty, check you're pointed at the right directory before anything else. ## The screen **Requests** (left) lists every request grouped by file, each row showing its state, method, id and description: | Mark | Meaning | |---|---| | `●` | Ready to run: every variable it needs resolves. | | `○` | Not ready: something is missing, usually a token another request captures. | | `✓` | Ran and passed every assertion and capture. | | `✗` | Ran and failed, or could not be sent at all. | | `-` | [`# @disabled`](https://apic.sh/format/#pauses-and-disabled-requests): dimmed, and skipped by f and a; enter still sends it. | | spinner | In flight. | Once a request has run, its status code and round trip sit at the right of the row (`200 12ms`), and the file heading above it rolls its requests up as `✓9 ✗1`, so a flow over a long file reads at a glance. A narrow pane sheds the timing first and the description second; the status code and the mark always stay. The colour of a status code is its class, not its verdict: a `404` a request asserts is still a `✓`. When the list is taller than the pane, the right of its title counts the rows out of view: `↑3 ↓8`. **Preview** is `apic describe` for the selected request: the URL template, headers, the body, auth, every variable with the source it resolved from, and the declared captures and asserts. Missing variables are called out with the request that would provide them. **Response** is one scroll in three labelled parts. Under `request` is the line that was sent, with every variable resolved. Under `response` is the status line, timing and size, a line saying where the time went (DNS, connect, TLS, first byte, total, and whether the connection was reused) and the body pretty-printed and syntax-highlighted. Under `checks` are the assertions and captures. H adds the headers and the body sent to the first part and the response headers to the second; c swaps in the equivalent curl command, and each further press the same request as HTTPie, PowerShell, Python, JavaScript and Go (see [`apic snippet`](https://apic.sh/cli/#apic-snippet)) before the response comes back. When a tab holds more than fits, the right of the tab strip says where you are in it: `top ↓`, `↑ 40% ↓`, `↑ end`. **Checks** shows each assertion with its actual *and* expected value, which is the fastest way to see why a check failed, plus everything the request captured, under the same `request`, `response` and `checks` rules as the response tab. **Session** lists the values captured for the current environment, the same ones `apic session` prints and the same ones later runs will use, and the cookies in the jar when `cookies: true` is set. x clears them after a confirmation. **History** lists the selected request's earlier responses in the current environment, newest first, and under them what changed between the last two: the status, then the body, compared as [`apic history diff`](https://apic.sh/cli/#apic-history) compares them. It needs `history: N` in `apic.yaml`; until then the tab says so. Every run from the UI adds an entry, including the requests a `# @ref` ran first. The status bar carries the project root, the environment, a spinner with progress and a running clock while a request is out, and the result of the last run. `demo` and `redact` badges show when `--demo` or `--redact` is in force, so a screenshot never hides that values were masked. On a narrow terminal the bar gives up the project root first, then the last result, then the environment, so the key hint and anything in flight stay in view. ## Keys | Key | Action | |---|---| | ↑/k, ↓/j | Move between requests | | g, G | First and last request | | / | Filter by id, URL, method, file or description; ↑/↓ move through the matches while you type, enter keeps the filter | | enter | Run the selected request | | f | Run every request in its file, in order, as a flow | | a | Run every request in the project | | esc | Cancel a run, clear the filter, or close an overlay | | tab/l, shift+tab/h | Next and previous tab | | 1 2 3 4 5 | Jump to preview, response, checks, session, history | | H | Toggle request and response headers | | c | Show the selected request as curl; again for HTTPie, PowerShell, Python, JavaScript, Go, then back to the response | | J, K | Scroll the right pane a line down or up | | pgup/ctrl+u, pgdn/ctrl+d | Scroll the right pane half a page | | e, E | Switch to the next and the previous environment | | r | Reload the project from disk | | o | Open the request's file at its line in `$EDITOR` | | x | Clear the session for this environment | | ? | Show every key | | q, ctrl+c | Quit | ## How it behaves - **One request at a time.** Runs are serialised, because they share the session and the values captured along the way. Starting a run while one is in flight says so rather than queueing; esc cancels. - **Flows update live.** Running a file sends its requests one after another, and each row turns green or red as its response arrives, so a long flow shows progress instead of a frozen screen. The cursor moves to each request as its response lands, so the pane shows the latest response while the next request is out, and a filter that would hide any of them is cleared when the flow starts, so the pane and the list always agree. - **Retries happen inside the run.** A request with `# @retry` is sent until its assertions pass; the status line of its response then says how many attempts it took. The row is "running" until then, so a long poll looks like a slow request. - **Captures apply immediately.** After `login` passes, requests that need `{{token}}` flip from `○` to `●` without a reload. A request with `# @ref login` is `●` from the start: running it runs `login` first when the token is missing, and `login`'s row shows that result too. - **Scrolling stays put.** Reading down a long response and it finishes changing underneath you (a later step of a flow landing, the terminal being resized) leaves you where you were. Moving to another request, tab or overlay starts at the top again. - **Switching environment rebuilds the project** with that environment's variables and session, and clears the results on screen, since they came from somewhere else. - **Editing is round-tripped.** o opens `$VISUAL`, then `$EDITOR` (`vi`, or `notepad` on Windows), at the request's line; the project is reloaded when the editor exits. VS Code, Cursor and VSCodium are given `--wait` so that moment is the tab closing, not the window opening. While the editor runs the UI stops reading the keyboard, so everything typed goes to the editor. r reloads without editing, which picks up files written by anything else. - **Redaction is honoured.** With `--redact`, bodies, header values, query values and captured values are masked on screen exactly as they are in `apic run --redact` output. ## If it will not start `apic ui` needs an interactive terminal on both stdin and stdout. - "needs an interactive terminal" means stdout is a pipe or a file. Drop the pipe, or use `apic run`/`apic list --json` for scripted work. - "does not support `--json`" means exactly that: the UI has no machine output. `apic run --json` and `apic list --json` do. - On Windows, run it in Windows Terminal or PowerShell. Git Bash's mintty needs `winpty apic ui`. - Below 70x16 the UI says the terminal is too small rather than drawing a scrambled screen. :::note[About the screenshot] The picture at the top is not a drawing. `task shots` serves the demo API in process, drives the UI the way the keys above do, and renders the frame it produces, escape codes and all, as SVG, so what the docs show is what the terminal shows. The moving picture on the [home page](https://apic.sh/) and the README is made the same way: twenty such frames captured after real key presses, cycled with SVG's own timing, so it needs no GIF and cannot drift from what the UI draws. ::: --- # Cheat sheet URL: https://apic.sh/cheatsheet/ Every directive, variable source, selector, assertion operator, auth type, command and exit code apic understands, on one page. Everything apic understands, on one page. Each section links to the full explanation. ## A file ```http @baseUrl = https://api.example.com # file variable, last one wins ### Log in and keep the token # separator; the title is the description # @name login # id used on the command line and by MCP # @assert status == 200 # @capture token = body.$.access_token POST {{baseUrl}}/auth/login Content-Type: application/json {"user": "{{user}}", "password": "{{password}}"} ``` ## Bodies | Body | Syntax | |---|---| | Inline | Everything after the blank line, `{{vars}}` substituted | | From a file | `< ./payload.json` as it is, `<@ ./payload.json` with `{{vars}}` substituted | | Multipart upload | `Content-Type: multipart/form-data; boundary=X`, parts between `--X` lines, `< ./report.pdf` as a part's content; see [format](https://apic.sh/format/#multipart-uploads) | | GraphQL | `GRAPHQL {{baseUrl}}/graphql` (or `X-REQUEST-TYPE: GraphQL`), the query as the body, variables as a JSON object after a blank line; sent as a JSON POST; see [format](https://apic.sh/format/#graphql) | | Save the response | `>> ./out.json` (create) or `>>! ./out.json` (overwrite) after the body; `apic run --output file` for one run; see [format](https://apic.sh/format/#saving-a-response) | | HTTP version | `GET https://x/ HTTP/1.1` never uses HTTP/2; `HTTP/2` requires it; none negotiates; see [format](https://apic.sh/format/#http-version) | ## Commands | Command | What it does | |---|---| | `apic run ...` | Send requests; several targets run in order as a flow; `--output file` saves one response body | | `apic run --data rows.csv` | Run once per row of a CSV file or JSON array; each row's columns are variables | | `apic run --assert --capture ` | A check or a capture for this run only, before writing it into the file | | `apic run --dry-run` | The request as it would be sent, resolved; nothing sent, nothing captured | | `apic run --body-limit 4k` | At most that much body in the output, marked `body_truncated`; the history keeps it all | | `apic ui` | [Terminal UI](https://apic.sh/tui/); `--demo` needs no project | | `apic test [paths]` | Run [Gherkin features](https://apic.sh/testing/) | | `apic list [pattern]` | Every request, filtered by id, URL, file or description | | `apic describe ` | Variables, sources, captures, asserts, readiness | | `apic env` | Environments and the variables in effect | | `apic session [clear]` | Captured values; `clear --all` for every environment | | `apic history ` | Past responses (needs `history: N` in `apic.yaml`; `apic init` sets 10); `--show 2`, `diff`, `clear ` or `clear --all` | | `apic select ` | A value from the last recorded response, without sending again; `--entry 2` for the one before | | `apic curl ` | The equivalent curl command | | `apic snippet --lang python` | The request as httpie, powershell, python, js or go code | | `apic init [dir]` | Scaffold a project, Agent Skill and `.mcp.json` included (`--no-skill`, `--no-mcp`) | | `apic skill [name]` | Print a briefing for an AI agent: `apic` (how to use apic, the default), `api-design` (how to design the API) or `api-security` (how to secure it and prove it) | | `apic skill install` | Write the `apic` skill into `.claude/skills` and `.agents/skills` of the project; `--all` adds `api-design` and `api-security`, `--skill ` picks exactly those, `--user` writes under your home directory so every project has them | | `apic import ` | `.http` files from an OpenAPI 3 document or a Postman collection (`--postman-env` for its environments) | | `apic import --curl '' --into f.http` | One request block from a curl command | | `apic validate` | Parse everything and report problems (CI); `--format github\|sarif` | | `apic fmt [--check\|--diff]` | Canonical formatting for `.http` files; `-` filters stdin; `file.http#name` for one request | | `apic mcp [install]` | Serve the project to agents over MCP, or register the server in `.mcp.json` | | `apic lsp` | Language server for any LSP editor ([set-up](https://apic.sh/editors/#any-editor-with-an-lsp-client)) | | `apic demo` | Scaffold and serve the bundled fake API | | `apic mock ` | Serve an OpenAPI 3 document as a stateless mock API; a `Prefer: code=404` header line picks another documented response | **Targets:** `get-user` (by name) · `users.http` (whole file as a flow) · `users.http#get-user` · `users.http#3` (third request). **Global flags:** `-C/--dir`, `-e/--env`, `--var k=v`, `--json`, `--no-color`, `--timeout`, `--no-session`, `--insecure`, `--cacert`, `--cert`, `--key`, `--redact`, `--cookies`, `--proxy`, `--no-proxy`. **Exit codes:** `0` ok · `1` assertion or capture failed · `2` usage, parse error, unknown request or missing variable · `3` network error. ## Directives Written as comments before the request line, so editors ignore them. | Directive | Meaning | |---|---| | `# @name get-user` | Id for the command line, MCP and features | | `# @description text` | One line shown by `list` and `describe` | | `# @capture name = selector` | Store a value from the response for later runs | | `# @assert selector op value` | Check the response; failures exit 1 | | `# @auth type ...` | `none`, `bearer`, `basic`, `apikey`, `digest`, `aws`, `oauth2`, `exec`; see [auth](https://apic.sh/auth/) | | `# @step a user named {name} exists` | Gherkin phrase that runs this request | | `# @ref login` | Run `login` first when a variable is missing | | `# @forceRef login` | Run `login` first every time | | `# @no-redirect` | Do not follow 3xx | | `# @no-session` | Do not persist this request's captures | | `# @no-cookies` | Send and keep no cookies for this request | | `# @timeout 10s` | Per-request timeout | | `# @retry 10 2s` | Re-send until the assertions pass, up to 10 times, 2s apart | | `# @sleep 2s` | Wait before sending | | `# @disabled` | Skipped when its file runs as a flow; `apic run ` still sends it | | `# @note text` | Free text, ignored (REST Client compatibility) | | `# @prompt name` | Ignored; pass the value with `--var name=...` instead | Unknown directives are warnings from `apic validate`, not errors. ## Variable precedence First match wins: 1. `--var name=value` (or `vars` in an MCP call) 2. `APIC_VAR_name` in the shell environment 3. values captured earlier in this run 4. the session, `.apic/session.json`, per environment 5. `http-client.private.env.json` for the environment 6. `http-client.env.json` for the environment (`$shared` applies to all) 7. `.env` in the project root 8. `@name = value` in the `.http` file `apic describe ` prints the source each variable actually resolved from. ## Built-in placeholders | Placeholder | Value | |---|---| | `{{$uuid}}` / `{{$guid}}` | random UUID v4 | | `{{$timestamp}}` / `{{$timestamp -1 d}}` | Unix seconds, optional offset (`s m h d w M Q y ms`) | | `{{$isoTimestamp}}` | RFC 3339 UTC | | `{{$datetime rfc1123\|iso8601\|"2006-01-02" [1 h]}}` | formatted UTC time, optional offset | | `{{$localDatetime [format] [offset]}}` | the same in the local zone | | `{{$randomInt 1 100}}` / `{{$random.integer(1, 100)}}` | random integer in [min, max) | | `{{$random.float(0, 1)}}`, `$random.alphabetic(n)`, `alphanumeric(n)`, `hexadecimal(n)`, `email`, `uuid` | JetBrains' random family | | `{{$processEnv NAME}}` / `{{$env.NAME}}` | shell environment variable | | `{{$dotenv NAME}}` | value from `.env` | | `{{$projectRoot}}` | absolute project root | | `{{$auth.token("name")}}` | token of a JetBrains `Security.Auth` configuration; see [auth](https://apic.sh/auth/#jetbrains-projects) | | `{{login.response.body.$.token}}` | an earlier response in the same flow | ## Selectors | Selector | Value | |---|---| | `status` | status code | | `statusText` | e.g. `OK` | | `header.` | first value of a response header; `.#` counts its values, `[1]` picks one | | `cookie.` | value of a cookie the response set | | `body` | raw body | | `body.$` | whole JSON body | | `body.$.` | `body.$.items[0].id`, `[-1]`, `[1:3]`, `[*]`, `body.$..id`, `body.$.items[?(@.done == true)].id`, `.#` or `.length` (count), `body.$["key.with.dots"]`; see [format](https://apic.sh/format/#body-paths) | | `duration` | round-trip time in milliseconds | ## Assertion operators `==` `!=` `<` `<=` `>` `>=` (numeric when both sides are numbers) · `contains` · `startsWith` · `endsWith` · `matches` (Go regexp) · `exists` · `not exists` · `isString` `isNumber` `isInteger` `isBoolean` `isArray` `isObject` `isNull` `isEmpty` (and `not …`) · `length ` · `matchesSchema ` ``` # @assert status < 300 # @assert body.$.items.# >= 1 # @assert header.content-type contains json # @assert body.$.email matches ^[^@]+@example\.com$ # @assert body.$.error not exists # @assert body.$.id isInteger # @assert body.$.items length == 3 # @assert body.$ matchesSchema ./schemas/user.json ``` ## Gherkin steps Built-in vocabulary, usable in any `.feature` file: ```gherkin Given the environment is "staging" And the variable "userId" is "42" And the variables: | userId | 42 | When I run "get-user" And I run "get-user" with: | userId | 7 | And I run the file "users.http" Then the response status is 200 And the response status is not 500 And the response is successful # or a client error, a server error And the response body "$.name" is "alice" And the response header "content-type" contains "json" And the response cookie "sid" exists And the response body "$.id" exists And the response body is: """ {"id": 42} """ And the response time is under 500 ms When I capture the response body "$.id" as "userId" ``` `# @step` phrases on requests add your own wording. `apic test --steps` lists everything available in the current project. ## Project layout ``` api/ apic.yaml env, dir, timeout, retry, cookies, history, proxy, noProxy, maxBodyBytes, tls, auth.default, auth.allowExec, test.paths features/*.feature Gherkin specs run by `apic test` http-client.env.json public per-environment variables http-client.private.env.json secrets (gitignored) .env optional KEY=value auth.http users.http .apic/session.json captured values (created by apic, self-ignored) .apic/cookies.json the cookie jar, when cookies: true ``` ## Terminal UI keys enter run · f run the file · a run all · / filter · 1-5 tabs · H headers · c curl · e/E environment · r reload · o edit · x clear session · ? help · q quit. Full list in [the TUI guide](https://apic.sh/tui/#keys). --- # From zero to apic URL: https://apic.sh/learn/ From zero to apic, a course in fourteen short lessons that takes you from nothing installed to running, testing and automating an API from .http files. A course in fourteen short lessons, each with a YouTube episode to follow. You start with nothing installed and finish able to describe an API in `.http` files, run it from the terminal, CI and an AI agent, and test it with Gherkin. Every lesson runs against `apic demo`, the fake API that ships inside apic, so you never need an account or a network connection to follow along. A few lessons add real APIs at the end for the full picture. ## How the lessons work Each lesson is one page with the same shape, so you always know where you are: | Section | What it is for | |---|---| | **Goal** | One sentence: what you can do when you finish. | | **You will need** | apic version, whether `apic demo` should be running, anything else. | | **Steps** | Numbered, each with the command to type and the output to expect. Copy, paste, compare. | | **Checkpoint** | One command whose output proves the lesson took. | | **Exercise** | One task to do on your own, with a collapsed solution. | | **Going further** | Links into the guides for the depth the lesson skipped. | | **Episode script** | Collapsed at the end: what the video says and shows, with chapter timestamps. | The commands in every lesson are run in CI against the demo API, so a lesson cannot quietly stop working when apic changes. The course is written for apic v0.2.0 or newer. The sample output comes from the current build, so a release can word an error's hint or link slightly differently; the commands and the results are the same. ## Syllabus | # | Lesson | You will learn | Episode | |---|---|---|---| | 0 | [What apic is and why](https://apic.sh/learn/00-what-is-apic/) | The problem, the idea, what the course builds | coming soon | | 1 | [Install apic and send your first request](https://apic.sh/learn/01-first-request/) | Install, `apic ui --demo`, the anatomy of a `.http` file, `run`, `list`, `describe`, exit codes | coming soon | | 2 | [Variables and environments](https://apic.sh/learn/02-variables-and-environments/) | Env files, secrets, `--var`, `APIC_VAR_`, the precedence order | coming soon | | 3 | [Capture, the session and flows](https://apic.sh/learn/03-capture-session-flows/) | `# @capture`, the session file, running a file, `# @ref` | coming soon | | 4 | [Assertions, validation and polling](https://apic.sh/learn/04-assertions/) | Selectors, operators, `validate`, `# @retry` | coming soon | | 5 | [The terminal UI tour](https://apic.sh/learn/05-terminal-ui/) | Every key with a purpose | coming soon | | 6 | [Authentication](https://apic.sh/learn/06-authentication/) | bearer, basic, API keys, OAuth2, AWS SigV4, `exec` | coming soon | | 7 | [Behaviour tests with Gherkin](https://apic.sh/learn/07-gherkin/) | `# @step`, features, reports | coming soon | | 8 | [CI without leaking secrets](https://apic.sh/learn/08-ci/) | GitHub Actions, `--redact`, JUnit | coming soon | | 9 | [From OpenAPI to a project, and back to curl](https://apic.sh/learn/09-import-export/) | `import`, `mock`, `curl`, Postman import | coming soon | | 10 | [Agents and MCP](https://apic.sh/learn/10-agents/) | The shell contract, `claude mcp add` | coming soon | | 11 | [Real APIs and the Taskfile front door](https://apic.sh/learn/11-real-apis/) | The httpbin, GitHub and Spotify examples | coming soon | | 12 | [Editors](https://apic.sh/learn/12-editors/) | The VS Code extension, JetBrains, Neovim | coming soon | | 13 | [How apic works inside, and contributing](https://apic.sh/learn/13-inside-apic/) | Architecture, a first pull request | coming soon | Every lesson is written; the episode column links to the video once it is recorded. Start with [lesson 0](https://apic.sh/learn/00-what-is-apic/), or jump straight to [lesson 1](https://apic.sh/learn/01-first-request/) if you already know why you are here. ## Before lesson 1 Nothing. Lesson 1 installs apic. If you want a head start: ```sh go install github.com/hungovercoders/apic/cmd/apic@latest # or see Getting started apic ui --demo ``` Press enter to send the request under the cursor, ? for the keys, q to quit. That is the whole tool in thirty seconds; the rest of the course is what you can do with it. ## Writing a lesson Contributions are welcome. [Writing a lesson](https://github.com/hungovercoders/apic/blob/main/docs/learn/_template.md) is the page template with the rules every lesson follows, and the [episode template](https://github.com/hungovercoders/apic/blob/main/docs/learn/_episode-template.md) is the YouTube description that goes with it. --- # Lesson 0: What apic is and why URL: https://apic.sh/learn/00-what-is-apic/ Lesson 0: the problem apic solves, what it is and is not, and what the course builds. **Goal.** Understand what apic is, what it is not, and what this course builds, so that lesson 1 is worth your time. ## You will need Nothing. This lesson has nothing to type; it is a watch-and-read. Lesson 1 installs apic. ## The problem You have an API to call. Every tool you reach for is good at one thing and stops there: - **Postman and Bruno are apps.** A request lives in a workspace, not in your repository. Running it in CI means another product, another account, another export format. - **`.http` files in VS Code or JetBrains are great until you leave the editor.** Click the link, read the response, done. Then you want to run the same file in a pipeline, from a script or from an AI agent, and there is no command for it. - **curl in a Taskfile runs anywhere** and has none of the rest: no environments, no way to pass a token from one call to the next, no assertions, no output a program can read without a pile of `jq`. So teams end up with all three: an app for exploring, an editor file for the person who wrote the endpoint, and a shell script for CI. They drift. ## The idea Take the format editors already understand, a plain `.http` file, and give it one static binary that runs it everywhere: ```http ### 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": "{{user}}", "password": "{{password}}"} ### Who am I # @name whoami # @ref login # @assert status == 200 GET {{baseUrl}}/me Authorization: Bearer {{token}} ``` Read it top to bottom. `###` starts a request and titles it. The request line, headers and body are exactly what REST Client and JetBrains send when you click them; they still work there. Everything apic adds is a comment, `# @something`, which editors ignore: - `# @name` gives the request an id you can type: `apic run login`. - `# @assert` checks the response, so a request is also a test. - `# @capture` keeps a value from the response, and apic remembers it between runs, in another shell, tomorrow, from an agent. - `# @ref login` says "if I am missing something login provides, run login first". `{{baseUrl}}` and `{{password}}` come from environment files, the same `http-client.env.json` the editors read, with secrets in a private file that is never committed. That is the whole design: files in git that humans, editors, CI and agents all run the same way. ## Sixty seconds of it Here is the terminal UI on the project that ships inside apic, sending a request, running a file as a flow, reading the checks and the captured values: ![apic ui --demo: send a request, run a file as a flow, read the checks, see what was captured](../assets/apic-demo.svg) And the same project from the command line: ```console $ apic run login whoami POST http://localhost:8089/auth/login 200 OK · 1 ms · 30 B { "access_token": "mock-token" } ✓ status == 200 ↳ token = mock-token GET http://localhost:8089/me 200 OK · 0 ms · 30 B { "email": "alice@example.com" } ✓ status == 200 ✓ body.$.email endsWith @example.com ✓ login 200 1 ms ✓ whoami 200 0 ms 2 passed · 2 requests · 1 ms ``` Add `--json` and every request becomes one JSON line a program can read. The exit code says whether the assertions passed. That is what CI and agents get: not a screenshot of a tool, but the same file. ## What it does, as a story - **Environments.** `dev`, `staging`, `prod` are entries in one file; `--env staging` switches. Secrets sit in a second file that git ignores. - **Tokens that persist.** Log in once. Every later command, in any shell, has the token, until you clear it. - **Assertions and flows.** A request checks its own response. A file runs top to bottom as a flow and stops at the first failure, or keeps going and reports. - **Auth a text file cannot do.** Bearer and basic are text. OAuth2 client credentials, AWS SigV4 and "run this CLI to get a token" are one `# @auth` line each. - **Gherkin without Cucumber.** `# @step I am logged in` on a request, and a `.feature` file can say it. No glue code. - **Built for agents.** `apic list`, `apic describe`, `apic run --json` and an MCP server, so an agent discovers and calls your API the way you do, with the same files. ## What it is not apic does not script. There is no JavaScript before or after a request, no loops, no plugins. Where other tools reach for code, apic has a directive (`# @retry`, `# @ref`, `# @capture`) or leaves it to the shell. The [comparison](https://apic.sh/comparison/) says where each tool is better, honestly. ## What the course builds Lessons 1 to 8 work against `apic demo`, a fake API that ships inside apic, so nothing needs an account or a network. You install apic, send a request, add environments, capture a token, write assertions and validate a project, tour the UI, authenticate five ways, write behaviour tests in Gherkin and run all of it in CI without leaking a secret. Lessons 9 to 13 go outward: importing an OpenAPI spec, driving apic from an agent, real APIs, editors, and how apic works inside. ## Checkpoint None. The exercise is the checkpoint. ## Exercise Install apic before the next episode. [Lesson 1](https://apic.sh/learn/01-first-request/) shows how for every platform, and takes a minute. ## Going further - [Why it's epic](https://apic.sh/), the same story in fewer words - [Comparison with other tools](https://apic.sh/comparison/) - [The `.http` format](https://apic.sh/format/), if you want to read ahead
Episode script **Length.** 5 to 7 minutes. **Cold open (0:00).** Three windows side by side: a Postman collection, a `.http` file in VS Code with its "Send Request" link, a Taskfile with a curl line. "Same API. Three copies. Which one is right?" **Talking points.** 1. The three tools and where each one stops (apps, editor-only files, curl with no environments or chaining). 2. The idea: the editor's file, plus comments, plus one binary. Read the two-request file aloud, line by line. 3. The sixty-second tour: the animated UI, then `apic run login whoami` in a terminal, then the same with `--json` piped into jq. 4. The story bullets, one line each, no detail. Environments, tokens that persist, assertions and flows, auth, Gherkin, agents. 5. What it is not, in one breath, and why that is a feature. 6. What the course builds and what you need for lesson 1 (nothing). **Shot list.** B-roll: `website/public/assets/apic-demo.svg` full screen; a Postman window next to the `.http` file; `apic run login whoami` in a 100x30 terminal; the same `.http` file in VS Code with the REST Client link clicked. No tape for this lesson: the terminal shots are `docs/learn/tapes/01.tape` from lesson 1. **Chapters.** `0:00 Three tools, three copies` · `1:10 One file` · `2:30 Sixty seconds of apic` · `3:40 What it does` · `5:00 What it is not` · `5:40 The course, and lesson 1`. **Thumbnail text.** "APIs from plain text files". **Description.** From the [episode template](https://github.com/hungovercoders/apic/blob/main/docs/learn/_episode-template.md).
--- # Lesson 1: Install apic and send your first request URL: https://apic.sh/learn/01-first-request/ Lesson 1: install apic, try apic ui --demo, read the anatomy of a .http file, and use run, list, describe and the exit codes. **Goal.** Install apic, run a request from a `.http` file against the demo API, and read the file that described it. ## You will need - A terminal. Nothing else: this lesson installs apic and the demo API ships inside it. ## Steps ### 1. Install apic One static binary, no runtime. Pick your platform: #### Homebrew (macOS and Linux) ```sh brew install hungovercoders/tap/apic ``` The cask installs the binary, the man pages and shell completions, and `brew upgrade` follows new releases. #### Linux / macOS without Homebrew ```sh curl -fsSL https://raw.githubusercontent.com/hungovercoders/apic/main/install.sh | sh ``` The installer puts `apic` in `~/.local/bin` (or `/usr/local/bin` when that is writable), verifies the release checksum, and prints where it landed. If the directory is not on your `PATH`, it says so. #### Windows In PowerShell: ```powershell irm https://raw.githubusercontent.com/hungovercoders/apic/main/install.ps1 | iex ``` The installer puts `apic.exe` in `%LOCALAPPDATA%\Programs\apic`, verifies the release checksum, and adds the directory to your user `PATH` (open a new terminal for other windows to see it). #### Go ```sh go install github.com/hungovercoders/apic/cmd/apic@latest # Go 1.26.11 or newer ``` This builds from source into `$(go env GOPATH)/bin`. In GitHub Actions, the [`setup-apic` action](https://apic.sh/cookbook/#a-smoke-test-in-ci-that-never-leaks-secrets) installs it in one step; lesson 8 uses it. Check it answers: ```sh apic version ``` ``` apic v0.2.0 · 1a2b3c4 · go1.26.11 linux/amd64 apic is epic · https://apic.sh/ ``` Your version and platform will differ; the shape is what matters. ### 2. Thirty seconds in the UI Before any files, see the tool move. `apic ui --demo` serves a fake API inside the process and opens the terminal UI on an example project that targets it: ```sh apic ui --demo ``` Four keys are enough for now: | Key | What it does | |---|---| | enter | Send the request under the cursor | | f | Run the whole file the cursor is in, as a flow | | ? | Every key | | q | Quit | Press enter on `login`. The right pane shows the status, the body and a green check. Press j to move down to `whoami` and enter again: it uses the token `login` just captured. Press q. Lesson 5 is the full tour; the rest of this course works from the command line, where every step is a command you can copy. ### 3. Start the demo API and look at the project `apic demo` writes the same example project to a directory and serves the API it targets. Leave it running in one terminal: ```sh apic demo --out apic-demo ``` ``` wrote apic-demo/apic.yaml wrote apic-demo/auth.http wrote apic-demo/explore.http wrote apic-demo/features/todos.feature wrote apic-demo/http-client.private.env.json wrote apic-demo/jobs.http wrote apic-demo/todos.http wrote apic-demo/http-client.env.json demo api listening on http://localhost:8089 try: apic run login whoami -C apic-demo --env local ``` In a second terminal, list what the project contains. `-C` tells every apic command which directory the project is in: ```sh apic list -C apic-demo ``` ``` ID METHOD URL LINE DESCRIPTION PHRASES auth.http login POST {{baseUrl}}/auth/login :9 Log in and keep the token I am logged in whoami GET {{baseUrl}}/me :20 Who am I, using the token captured by login (which runs first if needed) I ask who I am basic-auth GET {{baseUrl}}/basic-auth/{{user}}/{{password}} :28 Basic auth, encoded for you … todos.http list-todos GET {{baseUrl}}/todos :8 List todos I list the todos list-open-todos GET {{baseUrl}}/todos?done=false&page=1&limit=5 :18 Filter and paginate; the total comes back in a header I list the open todos … 24 requests in 4 files · apic describe · apic run · apic ui ``` Four files, twenty-four requests, each with an id you can type. The `PHRASES` column is for lesson 7. ### 4. Describe a request before sending it `describe` shows everything apic knows about a request without sending it: the method and URL, every variable it needs and where each one comes from, and whether it is ready. ```sh apic describe login -C apic-demo ``` ``` POST {{baseUrl}}/auth/login Log in and keep the token file: auth.http:9 headers Content-Type: application/json body {"user": "{{user}}", "password": "{{password}}"} variables ✓ baseUrl http://localhost:8089 http-client.env.json [local] ✓ user alice auth.http:1 @user ✓ password *** http-client.private.env.json [local] steps I am logged in captures ↳ token = body.$.access_token asserts status == 200 ╭──────────────────────────────╮ │ ready {{baseUrl}}/auth/login │ ╰──────────────────────────────╯ ``` Three variables, three different sources, and a password shown as `***` because it came from the private file. Lesson 2 is about that column. ### 5. Send it ```sh apic run login -C apic-demo ``` ``` POST http://localhost:8089/auth/login 200 OK · 1 ms · 30 B { "access_token": "mock-token" } ✓ status == 200 ↳ token = mock-token ``` Status, timing, size, the body, the assertion that passed, and the value that was captured. That last line is the one to remember: `token` is now stored, and every later request that says `{{token}}` will find it. ### 6. Read the file Open `apic-demo/auth.http` in any editor. The first request is: ```http @user = alice @clientId = demo-client ### Log in and keep the token # @name login # @step I am logged in # @assert status == 200 # @capture token = body.$.access_token POST {{baseUrl}}/auth/login Content-Type: application/json {"user": "{{user}}", "password": "{{password}}"} ``` Line by line: | Line | What it is | |---|---| | `@user = alice` | A file variable, available to every request in the file as `{{user}}`. | | `### Log in and keep the token` | The separator that starts a request, and its title. | | `# @name login` | The id. Without it the request would be `auth.http#1`. | | `# @step I am logged in` | A Gherkin phrase for lesson 7. Ignore it for now. | | `# @assert status == 200` | A check on the response. Lesson 4. | | `# @capture token = body.$.access_token` | Keep a value from the response. Lesson 3. | | `POST {{baseUrl}}/auth/login` | The request line: method and URL, with a variable. | | `Content-Type: application/json` | Headers, until the first blank line. | | `{"user": …}` | The body, until the next `###`. | Every line starting with `#` is a comment to any other tool that reads `.http` files, so this file still works in VS Code and JetBrains. The `# @` lines are apic's directives, and the [cheatsheet](https://apic.sh/cheatsheet/#directives) lists every one. ### 7. Exit codes Scripts and CI read the exit code before anything else. `0` means every assertion passed: ```sh apic run login -C apic-demo > /dev/null; echo "exit $?" ``` ``` exit 0 ``` The demo project has one request that fails its assertion on purpose: ```sh apic run not-found -C apic-demo || echo "exit $?" ``` ``` GET http://localhost:8089/status/404 404 Not Found · 1 ms · 15 B { "status": 404 } ✗ status == 200 (actual: 404) exit 1 ``` `1` is an assertion that failed. `2` is a mistake before anything was sent (a missing variable, a request id that does not exist) and `3` is the network. The [exit codes](https://apic.sh/cli/#exit-codes) table is the contract. ## Checkpoint `--json` prints one JSON object per request. If this prints `"ok":true`, apic is installed, the demo is up, and you have sent a request through both: ```sh apic run login -C apic-demo --json | grep -o '"ok":true' ``` ``` "ok":true ``` (With `jq` installed, `apic run login -C apic-demo --json | jq .ok` prints `true`.) ## Exercise The demo API has a `GET /health` endpoint that needs no token. Add a request for it, named `ping`, to `apic-demo/auth.http` (or to a new file in the same directory), and run it with `apic run ping -C apic-demo`.
Solution Appending a request to a new file keeps the shipped one clean: ```sh cat >> apic-demo/mine.http <<'EOF' ### Is the API up? # @name ping # @assert status == 200 GET {{baseUrl}}/health EOF apic run ping -C apic-demo ``` ``` GET http://localhost:8089/health 200 OK · 1 ms · 73 B { "service": "apic-demo", "status": "ok", "uptime_seconds": 12, "version": "v0.2.0" } ✓ status == 200 ``` `{{baseUrl}}` resolves in any file in the project because it comes from `http-client.env.json`, not from the file. The `###` line, `# @name` and the request line are the whole request; headers and a body are only there when the request needs them.
## Going further - [Getting started](https://apic.sh/getting-started/), the same steps for a real project - [The terminal UI](https://apic.sh/tui/), every key - [`apic run`](https://apic.sh/cli/#apic-run) and the [exit codes](https://apic.sh/cli/#exit-codes)
Episode script **Length.** 8 to 10 minutes. **Cold open (after the title card).** An empty terminal. "In ten minutes you will have sent a request from a text file, and understood every line of the file." **Talking points.** 1. Install: thirty seconds per platform, cut short. `apic version` proves it. 2. `apic ui --demo`: enter on login, j, enter on whoami. "That second request used the token the first one captured. Hold that thought for lesson 3." 3. `apic demo` in terminal one; `list`, `describe login`, `run login` in terminal two. Point at the three variable sources and the `***`. 4. The file, line by line, with the table on screen. 5. Exit codes: 0, then the deliberate 404 and its `✗` line, then the `1`. 6. The checkpoint, and the `--json` line it comes from. **Shot list.** Per-OS install as three short picture-in-picture clips; then one terminal, 100x30, font size 16. `docs/learn/tapes/01.tape` reproduces the terminal parts. Zoom on `↳ token = mock-token` after step 5 and on `exit 1` in step 7. **Chapters.** `0:00 Why` · `0:30 Install` · `1:40 The UI in thirty seconds` · `3:00 list, describe, run` · `5:20 The file, line by line` · `7:10 Exit codes` · `8:10 Checkpoint` · `8:40 Exercise and lesson 2`. **Description.** From the [episode template](https://github.com/hungovercoders/apic/blob/main/docs/learn/_episode-template.md).
--- # Lesson 2: Variables and environments URL: https://apic.sh/learn/02-variables-and-environments/ Lesson 2: every place a {{variable}} can come from, environment files, secrets, --var and APIC_VAR_, and the precedence order. **Goal.** Know every place a `{{variable}}` can come from, and which one wins when two of them have a value. ## You will need - apic installed ([lesson 1](https://apic.sh/learn/01-first-request/)) - `apic demo` running in another terminal, or start it now: ```sh apic demo --out apic-demo ``` ## Steps ### 1. The file itself The top of `apic-demo/auth.http` declares two variables: ```http @user = alice @clientId = demo-client ``` They are available to every request in that file, and `describe` says so in its source column: ```sh apic describe login -C apic-demo ``` ``` variables ✓ baseUrl http://localhost:8089 http-client.env.json [local] ✓ user alice auth.http:1 @user ✓ password *** http-client.private.env.json [local] ``` Three variables, three sources. This lesson is the story of that column. ### 2. The environment file `baseUrl` comes from `http-client.env.json`, the same file VS Code's REST Client and JetBrains read: ```sh cat apic-demo/http-client.env.json ``` ```json { "local": { "baseUrl": "http://localhost:8089" } } ``` One environment, `local`, one variable. A real project has `dev`, `staging` and `prod` here, each with its own `baseUrl`. Values every environment shares go under `$shared`. Give the demo a second environment. Move `baseUrl` to `$shared` so both environments use the same API, and give `staging` a different user (the first line reads the URL back from the current file, so the port stays whatever your demo is using): ```sh base=$(grep -o 'http://[^"]*' apic-demo/http-client.env.json | head -1) cat > apic-demo/http-client.env.json < ```sh apic describe login -C apic-demo --env staging ``` ``` variables ✗ password missing pass --var password=... ✓ baseUrl http://localhost:8089 http-client.env.json [staging] ✓ user bob http-client.env.json [staging] ╭────────────────────────────────╮ │ not ready missing {{password}} │ ╰────────────────────────────────╯ ``` Two things happened. `user` is now `bob` from the `staging` block, which beats the file's `@user = alice`. And `password` is missing, because the private file only knows `local`. Missing variables come first, with the way to fix them. Why did lesson 1 never need `--env`? Because `apic.yaml` sets the default: ```sh cat apic-demo/apic.yaml ``` ```yaml # Default environment when --env is not given. env: local ``` ### 4. Secrets The private file has the same shape and holds the values that must not be committed: ```sh cat apic-demo/http-client.private.env.json ``` ```json { "local": { "password": "s3cret", "clientSecret": "demo-secret", "apiKey": "demo-key" } } ``` `apic init` adds it to `.gitignore`; the demo project is a scratch directory, so it does not. Anything from this file is shown as `***` in `describe`, `env` and `run` output, so a secret never lands in a terminal log by accident. Give `staging` a password too: ```sh cat > apic-demo/http-client.private.env.json <<'EOF' { "local": { "password": "s3cret", "clientSecret": "demo-secret", "apiKey": "demo-key" }, "staging": { "password": "s3cret", "clientSecret": "demo-secret", "apiKey": "demo-key" } } EOF apic describe login -C apic-demo --env staging ``` ``` variables ✓ baseUrl http://localhost:8089 http-client.env.json [staging] ✓ user bob http-client.env.json [staging] ✓ password *** http-client.private.env.json [staging] ╭──────────────────────────────╮ │ ready {{baseUrl}}/auth/login │ ╰──────────────────────────────╯ ``` Ready. The demo API only knows `alice`, so sending this gets a `401`, which is exactly what a wrong environment looks like: ```sh apic run login -C apic-demo --env staging || echo "exit $?" ``` ``` POST http://localhost:8089/auth/login 401 Unauthorized · 1 ms · 27 B { "error": "bad credentials" } ✗ status == 200 (actual: 401) ✗ capture token: nothing at body.$.access_token exit 1 ``` The exercise fixes it. ### 5. `.env`, `--var` and the shell Three more sources, from the least to the most specific. A `.env` file in the project root, `KEY=value` per line, is read for every environment: ```sh echo "user=dave" > apic-demo/.env apic describe login -C apic-demo | grep ' user ' ``` ``` ✓ user *** .env ``` `dave` beat the file's `alice` (an env file beats `.env`, and `.env` beats a file variable; `local` has no `user`, so `.env` won). Values from `.env` are treated as secrets, hence the `***`. `--var` on the command line beats everything: ```sh apic describe login -C apic-demo --var user=erin | grep ' user ' ``` ``` ✓ user *** --var ``` And `APIC_VAR_` in the shell sits just under `--var`, which is how CI passes a secret in without writing a file: ```sh APIC_VAR_user=frank apic describe login -C apic-demo | grep ' user ' rm apic-demo/.env ``` ``` ✓ user *** shell APIC_VAR_user ``` ### 6. The order Highest first. The first source that has the name wins: | Source | Example | |---|---| | `--var name=value` | `apic run login --var user=erin` | | `APIC_VAR_name` in the shell | `APIC_VAR_user=frank apic run login` | | Captured earlier in this run | `# @capture token = …` on a request that ran first | | The session | `.apic/session.json`, from a previous run | | `http-client.private.env.json` | the current environment, then `$shared` | | `http-client.env.json` | the current environment, then `$shared` | | `.env` | `user=dave` | | `@name = value` in the file | `@user = alice` | Lesson 3 is about the two in the middle. ### 7. Built-in values Some values are generated per request rather than looked up: `{{$uuid}}`, `{{$isoTimestamp}}`, `{{$timestamp}}`, `{{$randomInt}}` and a few more. Put one in a body: ```sh cat > apic-demo/builtins.http <<'EOF' ### A todo with a title that is never the same twice # @name create-unique-todo # @assert status == 201 POST {{baseUrl}}/todos Authorization: Bearer {{token}} Content-Type: application/json {"title": "todo {{$uuid}} at {{$isoTimestamp}}"} EOF apic run login create-unique-todo -C apic-demo ``` ``` POST http://localhost:8089/todos 201 Created · 1 ms · 108 B { "id": "3", "title": "todo 0b6c1a2e-7d2f-4c1e-9a58-3f6c2b1e8d40 at 2026-09-20T05:42:21Z", "done": false } ✓ status == 201 ``` `login` went first in the same command, so `{{token}}` was captured before the todo was created. The [cheatsheet](https://apic.sh/cheatsheet/#built-in-placeholders) lists every built-in. ## Checkpoint `describe --json` reports the source of each variable. Override `baseUrl` from the command line and confirm the command line won: ```sh apic describe whoami -C apic-demo --var baseUrl=http://example.com --json | grep -o '"source": "--var"' ``` ``` "source": "--var" ``` (With `jq`: `… --json | jq '.variables[] | select(.name=="baseUrl") | .source'` prints `"--var"`.) ## Exercise Make `staging` log in. The demo API accepts only `alice`, so `staging` needs that user. Then log in with `--env staging` and show that its token is kept apart from `local`'s.
Solution Change the user in the `staging` block, then log in there: ```sh base=$(grep -o 'http://[^"]*' apic-demo/http-client.env.json | head -1) cat > apic-demo/http-client.env.json < /dev/null apic session -C apic-demo ``` ``` local ↳ token = mock-token staging ↳ token = mock-token ``` Captured values are stored per environment, so `local` and `staging` each have their own `token`. Two real environments would have two different tokens, and `apic run whoami --env staging` would use the right one.
## Going further - [Variables](https://apic.sh/format/#variables) in the format guide - [Variable precedence](https://apic.sh/cheatsheet/#variable-precedence) on the cheatsheet - [Why does a variable have the wrong value?](https://apic.sh/faq/#why-does-a-variable-have-the-wrong-value) in the FAQ - [Two environments, one command](https://apic.sh/cookbook/#two-environments-one-command)
Episode script **Length.** 10 minutes. **Cold open (after the title card).** `apic describe login` with the three-source variable table on screen. "Same request, three places the values come from. By the end you will know all eight, and the order." **Talking points.** 1. File variables: `@user = alice`, and the `auth.http:1 @user` source. 2. The env file: one environment now, `$shared` and `staging` added, `apic env` listing both. 3. `--env staging`: user changes, password goes missing. `apic.yaml` is why `--env` was never needed before. 4. Secrets: the private file, `***` everywhere, the 401 from a wrong environment. 5. `.env`, `--var`, `APIC_VAR_`: three commands, watch the source column change each time. 6. The order, as a table, read top to bottom once. 7. Built-ins in a body. 8. Checkpoint, then the exercise (a second environment with its own session). **Shot list.** One terminal, 100x30, font size 16, with the env file open in an editor split for steps 2 to 4. `docs/learn/tapes/02.tape` reproduces the terminal parts. Zoom on the source column after every change. **Chapters.** `0:00 Where do values come from` · `0:40 File variables` · `1:30 The environment file` · `3:00 --env and apic.yaml` · `4:20 Secrets` · `6:00 .env, --var, the shell` · `7:30 The order` · `8:20 Built-ins` · `9:00 Checkpoint and exercise`. **Description.** From the [episode template](https://github.com/hungovercoders/apic/blob/main/docs/learn/_episode-template.md).
--- # Lesson 3: Capture, the session and flows URL: https://apic.sh/learn/03-capture-session-flows/ Lesson 3: capture a value from a response, reuse it from the session in any later command, and run a whole file as a flow with # @ref. **Goal.** Capture a value from a response, reuse it in any later command, and run a whole file as a flow. ## You will need - apic installed ([lesson 1](https://apic.sh/learn/01-first-request/)) - `apic demo` running in another terminal, or start it now: ```sh apic demo --out apic-demo ``` ## Steps ### 1. The error you get without a token Start clean, then ask for the todo list, which needs a token. `--all` forgets every environment, including the `staging` token from lesson 2's exercise: ```sh apic session clear --all -C apic-demo apic run list-todos -C apic-demo || echo "exit $?" ``` ``` session cleared GET {{baseUrl}}/todos error: todos.http:8: missing variable {{token}}: it is captured by request "login"; run `apic run login` first, or pass --var token=... E101 missing variable · see https://apic.sh/errors/#e101 exit 2 ``` Nothing was sent: exit code `2` means apic stopped before the network. The error names the variable, the request that provides it, and the two ways to fix it. Take the first. ### 2. Capture `login` ends with a directive you saw in lesson 1: ```http # @capture token = body.$.access_token ``` `body.$.access_token` is a selector: the JSON body, then the path `access_token`. When the response arrives, whatever is there is stored under the name `token`: ```sh apic run login -C apic-demo ``` ``` POST http://localhost:8089/auth/login 200 OK · 1 ms · 30 B { "access_token": "mock-token" } ✓ status == 200 ↳ token = mock-token ``` Now the request from step 1 works, in this shell or any other, with no flag: ```sh apic run list-todos -C apic-demo --json | grep -o '"ok":true' ``` ``` "ok":true ``` ### 3. Where it went ```sh apic session -C apic-demo ``` ``` local ↳ token = mock-token ``` Captured values live in `.apic/session.json` under the project, keyed by environment, which is why lesson 2's `staging` token did not mix with `local`'s: ```sh cat apic-demo/.apic/session.json ``` ```json { "envs": { "local": { "token": "mock-token" } } } ``` apic writes a `.gitignore` next to it, so the file never reaches a commit: ```sh cat apic-demo/.apic/.gitignore ``` ``` # created by apic; session state must not be committed * ``` ### 4. Forgetting `session clear` empties the current environment (`--all` for every environment). `--no-session` on a command neither reads nor writes the file, which is what a CI job or a one-off check wants: ```sh apic session clear -C apic-demo apic run login -C apic-demo --no-session > /dev/null apic session -C apic-demo --json ``` ``` session cleared {} ``` `login` ran and captured its token for that one command, and nothing was kept. A request can also opt out on its own with `# @no-session`, for a value that must never be reused. ### 5. Reaching into an earlier response Within one command, a request can read another's response directly with `{{.response.}}`, without a capture. Write a request that uses `login`'s body: ```sh cat > apic-demo/chain.http <<'EOF' ### Who am I, reading login's response directly # @name me-by-ref # @assert status == 200 GET {{baseUrl}}/me Authorization: Bearer {{login.response.body.$.access_token}} EOF apic run login me-by-ref -C apic-demo --no-session ``` ``` … GET http://localhost:8089/me 200 OK · 0 ms · 30 B { "email": "alice@example.com" } ✓ status == 200 ✓ login 200 1 ms ✓ me-by-ref 200 0 ms 2 passed · 2 requests · 1 ms ``` This only works when `login` ran earlier in the same command, so it suits a flow in a file more than a request you run alone. `# @capture` is the one to reach for by default: it survives the command. ### 6. A file is a flow Naming a file instead of a request runs every request in it, in order, and prints a summary. `todos.http` creates a todo, reads it, updates it, deletes it and checks the delete stuck, each request using the id the first one captured: ```sh apic run login -C apic-demo > /dev/null apic run todos.http -C apic-demo || echo "exit $?" ``` ``` GET http://localhost:8089/todos 200 OK · 1 ms · 97 B … POST http://localhost:8089/todos 201 Created · 0 ms · 45 B … ✓ status == 201 ✓ body.$.title == Write docs ↳ todoId = 3 ↳ todoTitle = Write docs … GET http://localhost:8089/status/404 404 Not Found · 0 ms · 15 B ✗ status == 200 (actual: 404) ✓ list-todos 200 1 ms ✓ list-open-todos 200 0 ms ✓ create-todo 201 0 ms ✓ get-todo 200 0 ms ✓ update-todo 200 0 ms ✓ get-updated 200 0 ms ✓ delete-todo 204 0 ms ✓ get-deleted 404 0 ms ✓ create-todo-invalid 422 0 ms ✗ not-found 404 0 ms status == 200 (actual: 404) 1 failed, 9 passed · 10 requests · 1 ms exit 1 ``` Ten requests ran, then the flow stopped: `not-found` is the request that fails on purpose, and a flow stops at the first failure so a broken step does not cascade. The exit code is `1`. There are two more requests in the file; `--keep-going` runs them anyway and reports everything: ```sh apic run todos.http -C apic-demo --keep-going | tail -15 || true ``` ``` ✓ list-todos 200 1 ms ✓ list-open-todos 200 0 ms ✓ create-todo 201 0 ms ✓ get-todo 200 0 ms ✓ update-todo 200 0 ms ✓ get-updated 200 0 ms ✓ delete-todo 204 0 ms ✓ get-deleted 404 0 ms ✓ create-todo-invalid 422 0 ms ✗ not-found 404 0 ms status == 200 (actual: 404) ✓ redirect-followed 200 0 ms ✓ redirect-raw 302 0 ms 1 failed, 11 passed · 12 requests · 1 ms ``` Captures made during a flow are kept like any other, so `todoId` is in the session now, even though the todo it named was deleted. ### 7. Let the request ask for what it needs Step 1's error asked you to run `login` yourself. A request can say that for you. `whoami` in `auth.http` carries: ```http # @ref login ``` Clear the session and run it alone: ```sh apic session clear -C apic-demo apic run whoami -C apic-demo ``` ``` session cleared POST http://localhost:8089/auth/login 200 OK · 1 ms · 30 B { "access_token": "mock-token" } ✓ status == 200 ↳ token = mock-token ↳ ran login first (# @ref) GET http://localhost:8089/me 200 OK · 0 ms · 30 B { "email": "alice@example.com" } ✓ status == 200 ✓ body.$.email endsWith @example.com ``` `{{token}}` was missing, `login` is the request that captures it, so apic ran `login` first and then `whoami`. Run `whoami` again and only `whoami` goes out, because the token is there now. `# @forceRef login` would run it every time, for a token that must be fresh. `describe` knows about it too: a missing variable a `# @ref` supplies does not make a request "not ready". ## Checkpoint After a login, the session holds exactly one `token` for `local`: ```sh apic run login -C apic-demo > /dev/null && apic session -C apic-demo --json | grep -c '"token"' ``` ``` 1 ``` (With `jq`: `apic session -C apic-demo --json | jq .local.token` prints `"mock-token"`, and `null` after `apic session clear`.) ## Exercise Write a two-request file of your own: create a todo, capture its `id`, and fetch it back by that id. The demo API answers `POST /todos` with the todo it created, `id` included. Run the file as a flow.
Solution ```sh cat > apic-demo/mytodo.http <<'EOF' ### Create a todo and keep its id # @name my-create # @ref login # @assert status == 201 # @capture myId = body.$.id POST {{baseUrl}}/todos Authorization: Bearer {{token}} Content-Type: application/json {"title": "Finish lesson 3"} ### Fetch it back # @name my-fetch # @assert status == 200 # @assert body.$.title == Finish lesson 3 GET {{baseUrl}}/todos/{{myId}} Authorization: Bearer {{token}} EOF apic run mytodo.http -C apic-demo | tail -5 ``` ``` ✓ my-create 201 1 ms ✓ my-fetch 200 0 ms 2 passed · 2 requests · 1 ms ``` `myId` is captured by the first request and used by the second in the same flow. The `# @ref login` on the first means the file works from a cleared session too. `jobs.http` in the demo project does the same for a background job, and lesson 4 comes back to it.
## Going further - [Log in once and reuse the token everywhere](https://apic.sh/cookbook/#log-in-once-and-reuse-the-token-everywhere) - [Create, read, update, delete in one flow](https://apic.sh/cookbook/#create-read-update-delete-in-one-flow) - [Dependencies](https://apic.sh/format/#dependencies) and [flows](https://apic.sh/format/#flows) in the format guide - [`apic session`](https://apic.sh/cli/#apic-session)
Episode script **Length.** 10 to 12 minutes. **Cold open (after the title card).** `apic run list-todos` and the missing-variable error. "apic knows which request would fix this. By the end, the request will know too." **Talking points.** 1. The error: exit 2, nothing sent, the request that captures it. 2. `# @capture`, the `↳ token` line, and list-todos working with no flag. 3. `apic session`, the file, the `.gitignore` it ships with. 4. `session clear`, `--no-session`, `# @no-session`: three ways to forget. 5. Response references: one command, two requests, no capture. 6. `todos.http` as a flow: stops at not-found, exit 1, then `--keep-going` and the twelve-row summary. 7. `# @ref login`: clear, run whoami, watch login go first. Run it again and it does not. 8. Checkpoint and the exercise (create then fetch by id). **Shot list.** One terminal, 100x30, font size 16. `docs/learn/tapes/03.tape` reproduces the terminal parts. Zoom on `↳ token = mock-token`, on the `✗ not-found` row, and on `↳ ran login first (# @ref)`. **Chapters.** `0:00 The missing token` · `1:00 Capture` · `2:30 The session file` · `4:00 Forgetting` · `5:20 Response references` · `6:30 A file is a flow` · `8:40 # @ref` · `10:20 Checkpoint and exercise`. **Description.** From the [episode template](https://github.com/hungovercoders/apic/blob/main/docs/learn/_episode-template.md).
--- # Lesson 4: Assertions, validation and polling URL: https://apic.sh/learn/04-assertions/ Lesson 4: assert on status, headers and JSON with selectors and operators, read a failure, validate a project, and poll with # @retry. **Goal.** Assert on the status, headers and JSON of a response, read a failure, validate a project before running it, and wait for an API to reach a state. ## You will need - apic installed ([lesson 1](https://apic.sh/learn/01-first-request/)) - `apic demo` running in another terminal, or start it now: ```sh apic demo --out apic-demo ``` - A token in the session, so the requests that need one have it: ```sh apic run login -C apic-demo > /dev/null ``` ## Steps ### 1. A request that checks itself Every `# @assert` line is a check on the response. `health` in `explore.http` has three: ```http # @assert status == 200 # @assert body.$.status == ok # @assert body.$.version exists ``` ```sh apic run health -C apic-demo ``` ``` GET http://localhost:8089/health 200 OK · 1 ms · 73 B { "service": "apic-demo", "status": "ok", "uptime_seconds": 12, "version": "v0.2.0" } ✓ status == 200 ✓ body.$.status == ok ✓ body.$.version exists ``` Each assertion is `selector operator value`. The left side picks something from the response, the operator compares, the right side is what you expect (or nothing, for `exists`). ### 2. Reading a failure `not-found` asks for a 404 and asserts a 200, on purpose: ```sh apic run not-found -C apic-demo || echo "exit $?" ``` ``` GET http://localhost:8089/status/404 404 Not Found · 1 ms · 15 B { "status": 404 } ✗ status == 200 (actual: 404) exit 1 ``` The `✗` line shows the expression and what the selector actually found. Exit code `1` is what a script or CI reads. Nothing else changes: the response is still printed, and any capture on the request still happens. ### 3. Selectors The left side can be any of these: | Selector | Picks | |---|---| | `status` | The status code, `404` | | `statusText` | The reason, `Not Found` | | `duration` | Milliseconds the request took | | `header.` | A response header, case-insensitive | | `body` | The raw body as text | | `body.$` | The body as JSON | | `body.$.a.b` | A path into it | | `body.$[0]` | An array element | | `body.$.items.#` | How many elements `items` has | `list-open-todos` uses four of them on one response: ```http # @assert status == 200 # @assert header.x-total-count >= 1 # @assert body.$.# <= 5 # @assert body.$[0].done == false ``` ```sh apic run list-open-todos -C apic-demo -v ``` ``` GET http://localhost:8089/todos?done=false&page=1&limit=5 Authorization: *** HTTP/1.1 200 OK · 1 ms · 90 B dns 0 ms · connect 0 ms · tls 0 ms · ttfb 1 ms · total 1 ms · new connection content-length: 90 content-type: application/json date: Mon, 01 Jun 2026 09:00:00 GMT x-page: 1 x-total-count: 2 [ { "id": "1", "title": "Buy milk", "done": false } ] ✓ status == 200 ✓ header.x-total-count >= 1 ✓ body.$.# <= 5 ✓ body.$[0].done == false ``` `-v` shows the headers, so you can see `x-total-count` the second assertion read. `body.$.#` counted the array. `body.$[0].done` walked into its first element. The body does not have to be JSON. `daily-report` fetches CSV and asserts on the header and the raw text: ```http # @assert header.content-type contains text/csv # @assert body startsWith date,total,done,open ``` ### 4. Operators | Operator | Meaning | |---|---| | `==`, `!=` | Equal, not equal. Numbers compare as numbers, so `200 == 200.0` | | `<`, `<=`, `>`, `>=` | Numeric only; a non-number on either side fails with a reason | | `contains`, `startsWith`, `endsWith` | Substring checks on the text | | `matches` | A regular expression, `body.$.email matches ^[^@]+@example\.com$` | | `exists`, `not exists` | The selector found something, or found nothing; no right side | The right side can hold a variable: `body.$.id == {{userId}}` compares against whatever `userId` resolves to. ### 5. Errors are responses too An API's error shapes deserve assertions as much as its happy path. The demo answers an empty title with a 422 and a field map, and `create-todo-invalid` pins that down: ```http # @assert status == 422 # @assert body.$.error == "validation failed" # @assert body.$.fields.title exists ``` ```sh apic run create-todo-invalid -C apic-demo ``` ``` POST http://localhost:8089/todos 422 Unprocessable Entity · 1 ms · 69 B { "error": "validation failed", "fields": { "title": "must not be empty" } } ✓ status == 422 ✓ body.$.error == validation failed ✓ body.$.fields.title exists ``` Quotes around a value are optional and stripped, so `"validation failed"` and `validation failed` mean the same thing; quote when the value has leading or trailing spaces. In `apic ui`, the 3 key opens the checks tab, which lists every assertion of the selected request with its actual and expected values side by side, and lesson 5 spends time there. ### 6. Catching mistakes before a run An assertion with a typo in its selector fails every time, and a name used twice makes `apic run ` ambiguous. `apic validate` finds both without sending anything. Break a file on purpose: ```sh cat > apic-demo/broken.http <<'EOF' ### The same name as a request in explore.http # @name health # @assert stauts == 200 GET {{baseUrl}}/health EOF apic validate -C apic-demo || echo "exit $?" ``` ``` broken.http:2:9: warning: request name "health" is also used elsewhere; `apic run health` will be ambiguous (duplicate-name) broken.http:3:11: error: assert "stauts == 200": unknown selector "stauts" (unknown-selector) explore.http:2:9: warning: request name "health" is also used elsewhere; `apic run health` will be ambiguous (duplicate-name) ✗ 5 files, 25 requests, 1 error, 2 warnings exit 2 ``` Each line is `file:line:column`, the severity, the message and a code in parentheses. Editors and CI use the columns and codes: `--format github` turns them into annotations on a pull request, `--format sarif` feeds a code-scanning tool. Errors make `validate` exit `2`; warnings alone do not. Fix it by deleting the file, and confirm: ```sh rm apic-demo/broken.http apic validate -C apic-demo ``` ``` ✓ 4 files, 24 requests, no problems ``` (The counts include any files you added in the exercises.) ### 7. Waiting for a state Some assertions describe where an API is going, not where it is. The demo's job API moves a job from `queued` to `running` to `done`, one step per poll. Without help, you would loop in the shell: ```sh until apic run get-job -C apic-demo --json | grep -q '"state":"done"'; do sleep 1; done ``` `wait-for-job` in `jobs.http` says the same thing in one line: ```http # @retry 5 500ms # @assert status == 200 # @assert body.$.state == done ``` Submit a job, then run it: ```sh apic run create-job -C apic-demo > /dev/null apic run wait-for-job -C apic-demo ``` ``` attempt 1/5 · body.$.state == done: got "running" GET http://localhost:8089/jobs/1 200 OK · 1 ms · 26 B · 2 attempts { "id": "1", "state": "done" } ✓ status == 200 ✓ body.$.state == done ``` The first attempt found `running`, apic printed why and waited half a second, and the second attempt passed. Up to five would have been tried, and if none passed the last one would be reported as the failure, exit code `1`. A transport error counts as a failed attempt too. `--retry "5 500ms"` applies a policy to requests without their own, and `--no-retry` switches every policy off. ### 8. Assertions for programs `--json` carries every assertion with its outcome, so a script can say which one failed rather than only that one did: ```sh apic run not-found -C apic-demo --json || true ``` ```json {"ok":false,"request":{"name":"not-found",…},"response":{"status":404,…}, "asserts":[{"expr":"status == 200","pass":false,"actual":"404","expected":"200"}]} ``` `ok` is the one field to read first; `asserts[]` has the rest. A retried request adds `"attempts": 2`. ## Checkpoint Run the todo file with `--keep-going` and count the requests that failed. Exactly one does, the deliberate `not-found`: ```sh apic run todos.http -C apic-demo --keep-going --json | grep -c '"ok":false' ``` ``` 1 ``` (With `jq`: `… --json | jq -s 'map(select(.ok | not)) | length'` prints `1`, and `jq -s 'map(.ok) | all'` prints `false` because of that one.) ## Exercise Write a request for the first page of todos, two per page (`GET {{baseUrl}}/todos?page=1&limit=2`), with three assertions: the number of todos on the page, a response header, and a value inside the first todo.
Solution ```sh cat > apic-demo/paging.http <<'EOF' ### The first page of todos, two at a time # @name first-page # @ref login # @assert status == 200 # @assert body.$.# <= 2 # @assert header.x-page == 1 # @assert body.$[0].id exists GET {{baseUrl}}/todos ?page=1 &limit=2 Authorization: Bearer {{token}} EOF apic run first-page -C apic-demo | tail -4 ``` ``` ✓ status == 200 ✓ body.$.# <= 2 ✓ header.x-page == 1 ✓ body.$[0].id exists ``` `body.$.#` counts the array, `header.x-page` reads the header the API sets for the page you asked for, and `body.$[0].id` walks into the first element. The query string is written on continuation lines, which is easier to read than one long URL.
## Going further - [Selectors](https://apic.sh/format/#selectors) and [assertion operators](https://apic.sh/format/#assertion-operators) - [Retries](https://apic.sh/format/#retries) in the format guide - [`apic validate`](https://apic.sh/cli/#apic-validate), its formats and every diagnostic code - [Poll until something is ready](https://apic.sh/cookbook/#poll-until-something-is-ready)
Episode script **Length.** 12 minutes. **Cold open (0:00).** `apic run not-found` and the `✗ status == 200 (actual: 404)` line. "One line in the file, and the request is a test. This lesson is every kind of line you can write there." **Talking points.** 1. `health`: three assertions, three green checks, the shape `selector operator value`. 2. The failure: actual versus expected, exit 1. 3. Selectors on `list-open-todos` with `-v`: status, a header, a count, a path into the first element. CSV with `body startsWith`. 4. Operators, as a table, with the numeric rule. 5. Errors are responses: the 422 and its field map. 6. `apic validate` on a broken file: the columns, the codes, exit 2; delete it, `no problems`. 7. `# @retry` on `wait-for-job`: the attempt line, `2 attempts`, and the shell loop it replaces. 8. `--json` with the asserts array; the checkpoint; the exercise. **Shot list.** One terminal, 100x30, font size 16. `docs/learn/tapes/04.tape` reproduces the terminal parts. Zoom on the `✗` line in step 2, the `3:11` column in step 6, and `attempt 1/5` in step 7. **Chapters.** `0:00 One line makes it a test` · `0:50 A request that checks itself` · `1:50 Reading a failure` · `3:00 Selectors` · `5:00 Operators` · `6:00 Errors are responses too` · `7:20 validate` · `9:00 Waiting with # @retry` · `10:40 --json` · `11:20 Checkpoint and exercise`. **Description.** From the [episode template](https://github.com/hungovercoders/apic/blob/main/docs/learn/_episode-template.md).
--- # Lesson 5: The terminal UI tour URL: https://apic.sh/learn/05-terminal-ui/ Lesson 5: drive a whole project from apic ui, with every key that has a purpose: run, read, check, edit, reload. **Goal.** Drive a whole project from `apic ui` without touching the command line: run, read, check, edit, reload. ## You will need - apic installed ([lesson 1](https://apic.sh/learn/01-first-request/)) - `apic demo` running in another terminal, or start it now: ```sh apic demo --out apic-demo ``` - A terminal at least 70 columns by 16 rows. The UI says so if it is smaller. This lesson has no commands to copy after the first one: every step is a key. Keep the page beside the terminal. ## Steps ### 1. Open it ```sh apic ui -C apic-demo ``` ![apic ui on the demo project](../assets/apic-ui.svg) Four areas. **Requests** on the left, grouped by file, one row per request. On the right, a tab strip with **preview**, **response**, **checks**, **session** and **history**. The status bar at the bottom shows the project root, the environment, and the result of the last run. Nothing is different from the command line underneath: the same runner, the same session file, the same environment files. What you see here is what CI sees. If it refuses to start, that is by design: `apic ui` is the one interactive command, and it declines a pipe or `--json` rather than leave a script waiting on a screen. Everything else in apic is non-interactive. ### 2. Read the marks Every row starts with a mark: | Mark | Meaning | |---|---| | `●` | Ready: every variable it needs resolves | | `○` | Not ready: something is missing, usually a token another request captures | | `✓` | Ran and passed every assertion and capture | | `✗` | Ran and failed, or could not be sent | | spinner | In flight | On a fresh session most of `todos.http` is `○`: those requests need `{{token}}` and nothing has captured one yet. `whoami` is `●` even so, because its `# @ref login` promises to fetch it. Move the cursor with j and k (or the arrows) and watch the **preview** tab follow: it is `apic describe` for the selected request, with every variable and where it came from, and the missing ones called out with the request that would provide them. ### 3. Run one Put the cursor on `login` and press enter. The row shows a spinner, then `✓ 200 1ms`, and the right pane switches to the **response** tab: status line, body pretty-printed and highlighted, the assertion that passed, the value captured. Look left again: `list-todos`, `list-open-todos`, `create-todo` and `create-todo-invalid` have gone from `○` to `●`. The token landed in the session and the marks updated without a reload. The rows in between stay `○` for now: `get-todo` and its neighbours also need `todoId`, which only `create-todo` captures, and the flow in the next step is where you see those flip. That is [lesson 3](https://apic.sh/learn/03-capture-session-flows/) happening in front of you. Press H to add the request and response headers to the response tab, and again to hide them. Press c to swap the response for the equivalent `curl` command, ready to paste; press it again for HTTPie, PowerShell, Python, JavaScript and Go, and esc brings the response back. ### 4. Run a file Move down into `todos.http` and press f: run every request in the file the cursor is in, in order, as a flow. The rows light up one after another, each turning `✓` or `✗` as its response lands, and the file heading rolls them up: `todos.http ✓11 ✗1`. The `✗` is `not-found`, the request that fails on purpose; the flow carries on past it in the UI so you can see the whole file. The status bar says `last: 1 failed, 11 passed`. a does the same for the whole project. ### 5. Read a failure With the cursor on `not-found`, press 3 for the **checks** tab. It lists each assertion with its actual and expected values side by side: ``` ✗ status == 200 actual 404 expected 200 ``` For a long response, J and K scroll the right pane a line at a time, ctrl+d and ctrl+u half a page, and the right end of the tab strip says where you are: `top ↓`, `↑ 40% ↓`, `↑ end`. Scrolling stays put when a later step of a flow lands underneath you; moving to another request starts at the top again. ### 6. The session Press 4. The **session** tab lists the values captured for the current environment: `token`, `todoId`, `todoTitle`, exactly what `apic session` prints and what the next `apic run` will use. x clears them, after a confirmation. Do it, and watch `todos.http` go back to `○`. Then press enter on `login` again. ### 7. Find, switch, edit, reload - / filters the list as you type, by id, URL, method, file or description. Type `todo`, move through the matches with ↓ and ↑, press enter to keep the filter, and esc to clear it. - e switches to the next environment and E to the previous one. The project is rebuilt with that environment's variables and session, and the results on screen are cleared, because they came from somewhere else. If you did lesson 2's exercise, `staging` is one press away. - o opens the selected request's file at its line in `$VISUAL`, then `$EDITOR` (`vi` if neither is set, `notepad` on Windows). Save and quit, and the project is reloaded: a new request appears in the list, a changed assertion runs next time. r reloads without editing, for files changed by anything else. - ? shows every key. q quits. Started with `--redact`, the UI masks bodies, header values, query values and captures on screen exactly as `apic run --redact` does, and shows a `redact` badge in the status bar so a screenshot never hides that values were masked. `--demo` shows a `demo` badge the same way. ## Checkpoint Press g to go to the top, move onto any request in `todos.http`, and press f. When the flow finishes, the file heading reads `todos.http ✓11 ✗1`, the `✗` row is `not-found`, and the status bar says `last: 1 failed, 11 passed`. If it does, you have run, read and checked a flow without leaving the UI. ## Exercise Without quitting the UI, give `health` in `explore.http` a fourth assertion, `body.$.service == apic-demo`, and see it pass.
Solution Move the cursor onto `health`, press o, and the file opens at line 7 in your editor. Add the line under the other assertions: ```http # @assert body.$.version exists # @assert body.$.service == apic-demo GET {{baseUrl}}/health ``` Save and quit. The UI reloads the project. Press enter on `health`, then 3: four checks, four `✓`. If your editor is not what you expected, set `EDITOR` before starting the UI, for example `EDITOR=nano apic ui -C apic-demo`.
## Going further - [The terminal UI](https://apic.sh/tui/), every key and how it behaves - [`apic ui`](https://apic.sh/cli/#apic-ui) in the reference, including why it refuses pipes
Episode script **Length.** 8 minutes, almost entirely screen. **Cold open (0:00).** The UI opening on the demo, cursor on `login`, `todos.http` all `○`. "Every request in the project, and whether it can run right now. Watch what one key does." **Talking points.** 1. The four areas and the marks. Move the cursor; the preview follows. 2. enter on `login`: the response tab, and the `○` marks flipping to `●` on the left. Pause on that. 3. H and c on the response. 4. f on `todos.http`: rows lighting up in order, the file heading rolling up `✓11 ✗1`. 5. 3 on `not-found`: actual versus expected. 6. 4, x, marks back to `○`, `login` again. 7. /, e, o with the exercise edit live, r, ?. 8. `--redact` badge; why it refuses pipes and `--json`. **Shot list.** One terminal, 112x30, font size 16, nothing else on screen. `docs/learn/tapes/05.tape` drives everything except the editor round trip in step 7, which is recorded by hand because the editor is the viewer's own; it is `docs/assets/demo.tape` extended with the session, filter and environment flows. **Chapters.** `0:00 One key` · `0:40 The screen and the marks` · `1:40 Run one` · `2:40 Run a file` · `3:50 Read a failure` · `4:50 The session` · `5:40 Find, switch, edit, reload` · `7:10 Checkpoint and exercise`. **Description.** From the [episode template](https://github.com/hungovercoders/apic/blob/main/docs/learn/_episode-template.md).
--- # Lesson 6: Authentication URL: https://apic.sh/learn/06-authentication/ Lesson 6: attach credentials with # @auth per request and per project: bearer, basic, API keys, OAuth2, AWS SigV4 and exec. **Goal.** Attach credentials to requests with `# @auth`, per request and per project, and know what apic shows and what it hides. ## You will need - apic installed ([lesson 1](https://apic.sh/learn/01-first-request/)) - `apic demo` running in another terminal, or start it now: ```sh apic demo --out apic-demo ``` The demo API accepts any bearer token, HTTP basic auth for `alice`, an API key, and a client-credentials token endpoint, so every kind of auth in this lesson runs offline. The two real providers at the end are prose. ## Steps ### 1. Bearer, by hand and by directive You have been doing auth since lesson 1. `whoami` writes the header itself: ```http GET {{baseUrl}}/me Authorization: Bearer {{token}} ``` The directive form does the same thing: ```http # @auth bearer {{token}} GET {{baseUrl}}/me ``` Two differences. A directive can be a project default (step 5), so you do not repeat the header in every request. And whatever apic adds for you is never printed: only headers you wrote yourself appear in `-v`, and even those are masked when they carry a credential: ```sh apic run login -C apic-demo > /dev/null apic run whoami -C apic-demo -v | head -3 ``` ``` GET http://localhost:8089/me Authorization: *** ``` (The login first is so that `whoami`'s `# @ref login` has nothing to do; on a fresh session it would run `login` and print that report before its own.) ### 2. Basic Basic auth is the one you cannot write as a plain header, because the value is base64 of `user:password`. Let apic do it: ```http # @auth basic {{user}} {{password}} GET {{baseUrl}}/basic-auth/{{user}}/{{password}} ``` ```sh apic run basic-auth -C apic-demo ``` ``` GET http://localhost:8089/basic-auth/alice/s3cret 200 OK · 1 ms · 23 B { "authenticated": true } ✓ status == 200 ✓ body.$.authenticated == true ``` `apic curl` maps every auth type onto curl where curl has an equivalent, which for basic is `--user`: ```sh apic curl basic-auth -C apic-demo ``` ``` curl -sS \ --user 'alice:s3cret' \ 'http://localhost:8089/basic-auth/alice/s3cret' ``` ### 3. An API key An API key is a header with a secret in it. Write the header, keep the value in the private file, and apic masks it because of where it came from: ```http GET {{baseUrl}}/keyed X-Api-Key: {{apiKey}} ``` ```sh apic run api-key -C apic-demo -v | head -3 ``` ``` GET http://localhost:8089/keyed X-Api-Key: *** ``` `Authorization`, `X-Api-Key`, `Cookie` and a few other header names are always masked, and so is any header whose value came from a secret source: the private env file, `.env`, the session, a capture, `--var` or `APIC_VAR_`. ### 4. OAuth2 client credentials Machine-to-machine OAuth2 is one line. The demo has a token endpoint: ```http # @auth oauth2 tokenUrl={{baseUrl}}/oauth/token clientId={{clientId}} clientSecret={{clientSecret}} GET {{baseUrl}}/me ``` `describe` shows the spec and whether its variables resolve, before anything is sent: ```sh apic describe oauth2-token -C apic-demo ``` ``` GET {{baseUrl}}/me Client-credentials token, fetched and cached automatically file: auth.http:34 auth oauth2 tokenUrl={{baseUrl}}/oauth/token clientId={{clientId}} clientSecret={{clientSecret}} (request) variables ✓ baseUrl http://localhost:8089 http-client.env.json [local] ✓ clientId demo-client auth.http:2 @clientId ✓ clientSecret *** http-client.private.env.json [local] ``` Run it, then look at the session: ```sh apic run oauth2-token -C apic-demo > /dev/null apic session -C apic-demo ``` ``` local ↳ $oauth2:ba9f21f030e5a6f3 = token, expires in 1h0m0s ↳ token = mock-token ``` apic fetched a token from the token endpoint, sent the request with it, and cached the token in the session keyed by token URL, client id, grant and scope. Every later request with the same spec reuses it until a minute before it expires, then refreshes it. `apic session clear` forgets it; `--no-session` fetches a fresh one every time. In `--json`, the request records which auth type applied and nothing else about it: ```sh apic run oauth2-token -C apic-demo --json | grep -o '"auth":"[a-z0-9]*"' ``` ``` "auth":"oauth2" ``` **A real provider.** The repository's `examples/spotify` project does this against the Spotify Web API with `grant=client_credentials clientAuth=basic`, the client id and secret in the private file, and `apic session` showing the cached token with its lifetime. Entra ID, Okta, Auth0, Keycloak and Cognito all speak the same grant, so the line is the same with a different `tokenUrl`. **A human at a keyboard.** `grant=device_code` prints a URL and a code, waits while you approve in a browser, and caches the token like any other. It is for people, not agents: an unattended run would wait until the code expired. `grant=authorization_code` (with PKCE) is the other one for people: it opens a browser once and caches the token, and it never starts under `--json`, MCP or without a terminal; see [auth.md](https://apic.sh/auth/). ### 5. A project default, and opting out Most projects authenticate every request the same way. Say it once in `apic.yaml` instead of on each request. Make a small project beside the demo to see it (the demo API accepts any bearer token, so a fixed one in the private file will do here): ```sh base=$(grep -o 'http://[^"]*' apic-demo/http-client.env.json | head -1) mkdir -p apic-auth cat > apic-auth/http-client.env.json < apic-auth/http-client.private.env.json <<'EOF' { "local": { "token": "mock-token" } } EOF cat > apic-auth/apic.yaml <<'EOF' env: local auth: default: bearer {{token}} EOF cat > apic-auth/api.http <<'EOF' ### Uses the project default # @name me # @assert status == 200 GET {{baseUrl}}/me ### Public, so it opts out # @name health # @auth none # @assert status == 200 GET {{baseUrl}}/health EOF apic run me health -C apic-auth | tail -4 ``` ``` ✓ me 200 1 ms ✓ health 200 0 ms 2 passed · 2 requests · 1 ms ``` `me` has no auth line and no `Authorization` header, and was sent with the bearer token from the default. `health` said `# @auth none` and was sent with nothing. A request with its own `# @auth basic …` would use that instead. `describe` names the source: ```sh apic describe me -C apic-auth | sed -n 5,6p ``` ``` auth bearer {{token}} (apic.yaml) ``` Because the default may hold `{{variables}}`, one project can point at a different identity provider per environment: `tokenUrl` and `clientId` in the public env file, `clientSecret` in the private one, and a default of `oauth2 tokenUrl={{tokenUrl}} clientId={{clientId}} clientSecret={{clientSecret}}`. ### 6. A token from any command When the credential comes from a tool (`gcloud`, `az`, `op`, `vault`), `# @auth exec` runs it and uses its output: ```sh cat >> apic-auth/api.http <<'EOF' ### A token from a command # @name me-exec # @auth exec echo mock-token # @assert status == 200 GET {{baseUrl}}/me EOF apic validate -C apic-auth apic run me-exec -C apic-auth || echo "exit $?" ``` ``` api.http:14:9: warning: @auth exec will be refused until apic.yaml sets auth.allowExec: true (exec-disabled) ! 1 file, 3 requests, 1 warning GET {{baseUrl}}/me error: api.http:16: auth: @auth exec is disabled: set `auth: allowExec: true` in apic.yaml to let request files run "echo mock-token" hint: Check the # @auth spec (or auth.default), its credentials, and the token endpoint. E105 authentication failed · see https://apic.sh/errors/#e105 exit 2 ``` Refused, on purpose: a request file that runs commands deserves a deliberate yes, because agents edit request files. The project opts in: ```sh cat > apic-auth/apic.yaml <<'EOF' env: local auth: default: bearer {{token}} allowExec: true EOF apic run me-exec -C apic-auth | head -2 ``` ``` GET http://localhost:8089/me 200 OK · 1 ms · 30 B ``` The command runs directly, not through a shell, and its trimmed output becomes the `Authorization: Bearer …` header; `header=` and `prefix=` change that, and `ttl=30m` caches the output in the session. ### 7. AWS Signature V4 Signing a request for API Gateway, S3 or Lambda is one directive, and apic finds the keys the way the AWS CLI does: the environment, then `~/.aws/credentials`, then the CLI itself for SSO sessions and assumed roles. There is no AWS SDK inside apic; the signature is implemented and checked against the official test vectors. ```http # @auth aws service=execute-api region=eu-west-2 GET {{baseUrl}}/orders ``` Without an AWS account, `apic curl` still shows what the signed request would be, with fake keys in the environment: ```sh cat >> apic-auth/api.http <<'EOF' ### Signed for API Gateway # @name signed # @auth aws service=execute-api region=eu-west-2 GET {{baseUrl}}/health EOF AWS_ACCESS_KEY_ID=AKIAEXAMPLE AWS_SECRET_ACCESS_KEY=example apic curl signed -C apic-auth ``` ``` curl -sS \ --aws-sigv4 'aws:amz:eu-west-2:execute-api' \ --user "$AWS_ACCESS_KEY_ID:$AWS_SECRET_ACCESS_KEY" \ ${AWS_SESSION_TOKEN:+-H} \ ${AWS_SESSION_TOKEN:+x-amz-security-token:$AWS_SESSION_TOKEN} \ 'http://localhost:8089/health' ``` Against a real API Gateway with a real key pair, `apic run signed` sends the `Authorization: AWS4-HMAC-SHA256 …` header, `X-Amz-Date` and `X-Amz-Content-Sha256`, and shows none of them in its output. The [cookbook](https://apic.sh/cookbook/#aws-api-gateway-with-sigv4) has the full recipe and the [FAQ](https://apic.sh/faq/#my-aws-request-comes-back-403) the usual reasons for a 403. ## Checkpoint The OAuth2 request goes through the whole flow, token endpoint included, and reports the auth type it used: ```sh apic run oauth2-token -C apic-demo --json | grep -o '"auth":"oauth2"' ``` ``` "auth":"oauth2" ``` ## Exercise Move the demo project onto a default. Set `auth.default: bearer {{token}}` in `apic-demo/apic.yaml`, delete every `Authorization: Bearer {{token}}` header from `todos.http`, and make `apic run todos.http --keep-going` and `apic test` pass as before. One request will need to opt out; find it.
Solution `apic-demo/apic.yaml`: ```yaml env: local auth: default: bearer {{token}} ``` Delete the `Authorization:` line from each request in `todos.http`. Then run `apic test -C apic-demo` and every scenario fails: `login` now needs `{{token}}` too, because the default applies to every request without its own `# @auth`, and `login` is the request that produces the token. It opts out: ```http ### Log in and keep the token # @name login # @auth none ``` Now the flow shows `1 failed, 11 passed` (the deliberate `not-found`) and `apic test -C apic-demo` passes every scenario. Requests with their own `# @auth`, like `basic-auth` and `oauth2-token`, were never affected: a request's own directive wins over the default.
## Going further - [Authentication](https://apic.sh/auth/), every type and option - [OAuth2 client credentials](https://apic.sh/cookbook/#oauth2-client-credentials) and [AWS API Gateway with SigV4](https://apic.sh/cookbook/#aws-api-gateway-with-sigv4) in the cookbook - [What appears in output](https://apic.sh/auth/#what-appears-in-output)
Episode script **Length.** 14 minutes. The Spotify and AWS segments are prerecorded and short. **Cold open (0:00).** `apic run whoami -v` with `Authorization: ***`. "apic will add a credential to a request five different ways, and never print one. Here are all five." **Talking points.** 1. Bearer by hand and by directive; why the directive exists. 2. Basic on the demo, and `apic curl` turning it into `--user`. 3. The API key header, masked because of where the value came from. 4. OAuth2: `describe`, run, `apic session` with the cached token and its lifetime, `"auth":"oauth2"` in JSON. Cut to Spotify for thirty seconds: the same line, a real token. 5. A project default in `apic.yaml`, `# @auth none`, `describe` naming the source. 6. `exec`: refused, then allowed, and why it is off by default. 7. AWS: the directive, `apic curl` with fake keys, then a prerecorded call to a real API Gateway. 8. Checkpoint, then the exercise: the default on the demo and the one request that must opt out. **Shot list.** One terminal, 100x30, font size 16; `docs/learn/tapes/06.tape` reproduces the demo-only parts. Picture in picture for the Spotify developer dashboard and the AWS console. **Chapters.** `0:00 Five ways, never printed` · `0:50 Bearer` · `2:00 Basic` · `3:00 API keys` · `4:00 OAuth2` · `7:00 A project default` · `8:40 exec` · `10:20 AWS SigV4` · `12:30 Checkpoint and exercise`. **Description.** From the [episode template](https://github.com/hungovercoders/apic/blob/main/docs/learn/_episode-template.md).
--- # Lesson 7: Behaviour tests with Gherkin URL: https://apic.sh/learn/07-gherkin/ Lesson 7: declare # @step phrases on requests, write a .feature file with the built-in vocabulary, run it and read the report. **Goal.** Write a feature file that exercises the demo API using the built-in steps and the phrases you declare on requests, and read its report. ## You will need - apic installed ([lesson 1](https://apic.sh/learn/01-first-request/)) - `apic demo` running in another terminal, or start it now: ```sh apic demo --out apic-demo ``` ## Steps ### 1. Run the suite that ships with the demo The demo project has a `features/` directory with one file in it. `apic test` runs every `.feature` file under it: ```sh apic test -C apic-demo | tail -3 ``` ``` 8 scenarios (8 passed) 47 steps (47 passed) 30.251252ms ``` Open `apic-demo/features/todos.feature`. The first scenario reads: ```gherkin Feature: Todos Background: Given I am logged in Scenario: The list always has something in it When I list the todos Then the response status is 200 And the response body "$.#" is not "0" ``` No step definitions, no Cucumber runtime, no glue code. Every line is either a step apic ships or a phrase a request in this project declared. That is the whole language, and it is the thing no other `.http` tool has. ### 2. Read the vocabulary ```sh apic test --steps -C apic-demo ``` ``` built-in steps the environment is "" switch the scenario to another environment the variable "" is "" set a variable for later steps I run "" send a request by id; fails if its # @assert or # @capture fail I run "" with: (table name | value) send a request with variables I run the file "" send every request in a file, stopping at the first failure the response status is / is not status code the response body "" is "" also: is not, contains, starts with, ends with, matches; like $.items[0].id, $..id or $.items[?(@.done == true)].id the response header "" is "" same operators as for the body the response body "" exists / does not exist presence of a value the response body is: (doc string) semantic JSON equality the response body contains: (doc string) JSON subset match … phrases declared in this project I am logged in runs login (auth.http) … I wait for the job runs wait-for-job (jobs.http) I list the todos runs list-todos (todos.http) … a todo titled {title} is created runs create-todo (todos.http) … ``` Two halves. The built-in steps run requests by id and check the last response. The phrases are the `# @step` lines on requests in this project, so the second half is yours to grow. ### 3. Your first feature The smallest possible scenario runs a request by id and checks the status: ```sh cat > apic-demo/features/first.feature <<'EOF' Feature: Logging in Scenario: Good credentials get a token When I run "login" Then the response status is 200 And the response body "$.access_token" exists EOF apic test features/first.feature -C apic-demo | tail -3 ``` ``` 1 scenarios (1 passed) 3 steps (3 passed) 2.1ms ``` Feature paths are relative to the project root, like everything else under `-C`. A run step fails when the request cannot be sent, when any `# @assert` on it fails, or when a `# @capture` finds nothing, so the assertions you wrote in lesson 4 are already part of every scenario that runs the request. ### 4. Phrases, tables, doc strings and outlines `I run "create-todo"` works, but `a todo titled "Learn Gherkin" is created` reads like behaviour. `create-todo` declares that phrase: ```http ### Create a todo # @name create-todo # @step a todo titled {title} is created ``` `{title}` becomes a variable for that request. The built-in `I run "…" with:` step does the same with a table, for requests without a phrase. Doc strings compare the whole body, and a `Scenario Outline` runs once per row of its `Examples`: ```sh cat > apic-demo/features/lesson7.feature <<'EOF' Feature: Todos, my way Background: Given I am logged in Scenario: Create a todo and read it back When a todo titled "Learn Gherkin" is created Then the response status is 201 And the response body "$.title" is "Learn Gherkin" When I fetch the todo Then the response body contains: """ {"title": "Learn Gherkin", "done": false} """ Scenario Outline: The starter todos can be fetched by id When I run "get-todo" with: | todoId | | | todoTitle | | Then the response status is 200 And the response body "$.title" is "<title>" Examples: | id | title | | 1 | Buy milk | | 2 | Read the apic docs | EOF apic test features/lesson7.feature -C apic-demo | tail -3 ``` ``` 3 scenarios (3 passed) 14 steps (14 passed) 9.8ms ``` `I fetch the todo` used `todoId` and `todoTitle` that `create-todo` captured a step earlier; captures flow through a scenario the way they flow through a run. `the response body contains:` is a subset match, so the `id` the API added does not have to be in the doc string; `the response body is:` would demand the whole thing. The outline supplied both variables `get-todo` needs from its table, twice. ### 5. Tags A tag on a feature or a scenario, and `--tags` to choose: <!-- learn --> ```sh cat > apic-demo/features/tagged.feature <<'EOF' @smoke Feature: Tagged Scenario: The API answers When the API is up Then the response status is 200 @slow Scenario: The slow route takes its time When I run "slow" Then the response status is 200 EOF apic test features/tagged.feature -C apic-demo --tags '@smoke && ~@slow' | tail -3 ``` ``` 1 scenarios (1 passed) 2 steps (2 passed) 1.5ms ``` `,` is or, `&&` is and, `~` is not. A smoke suite in CI is a tag expression away. ### 6. Every scenario starts clean Scenarios do not share state with each other or with `apic run`. Each one begins with an empty in-memory session, and nothing it captures reaches `.apic/session.json`. Even with a token in your session from earlier, a scenario that skips the login has none: <!-- learn --> ```sh apic run login -C apic-demo > /dev/null cat > apic-demo/features/iso.feature <<'EOF' Feature: Isolation Scenario: Needs a token but never logged in When I list the todos Then the response status is 200 EOF apic test features/iso.feature -C apic-demo --format progress || echo "exit $?" ``` ``` F- 2 --- Failed steps: Scenario: Needs a token but never logged in # /home/you/apic-demo/features/iso.feature:2 When I list the todos # /home/you/apic-demo/features/iso.feature:3 Error: todos.http:8: missing variable {{token}}: it is captured by request "login"; run `apic run login` first, or pass --var token=... 1 scenarios (1 failed) 2 steps (1 failed, 1 skipped) 2.0ms error: todos.http:8: missing variable {{token}}: it is captured by request "login"; run `apic run login` first, or pass --var token=... E101 missing variable · see https://apic.sh/errors/#e101 exit 2 ``` That is why the shipped feature has `Background: Given I am logged in`: it runs once per scenario. `--use-session` shares the persisted session instead, for a slow identity provider you would rather not hit twenty times: <!-- learn --> ```sh apic test features/iso.feature -C apic-demo --use-session | tail -3 rm apic-demo/features/iso.feature ``` ``` 1 scenarios (1 passed) 2 steps (2 passed) 1.7ms ``` ### 7. A step that does not exist A misspelt or invented step is never silently skipped: <!-- learn --> ```sh cat > apic-demo/features/undefined.feature <<'EOF' Feature: A typo Scenario: Undefined When I do something apic has never heard of Then the response status is 200 EOF (apic test features/undefined.feature -C apic-demo --format progress || echo "exit $?") | grep -E "scenarios|steps|exit" rm apic-demo/features/undefined.feature ``` ``` 1 scenarios (1 undefined) 2 steps (1 undefined, 1 skipped) You can implement step definitions for undefined steps with these snippets: exit 1 ``` (The snippets it offers are godog's, the Gherkin engine inside apic, and are not something apic can use.) An undefined step counts as a failure, and `--steps` is where to look for the wording that exists. There is no way to add step code, and that is the point: the vocabulary plus your phrases is the whole language, so a feature is always readable by someone who knows neither Go nor apic. ### 8. Reports `--format` picks the report: `pretty` (the default), `progress`, `junit` for CI dashboards, and `cucumber` (or `--json`) for the tools that read Cucumber JSON: <!-- learn --> ```sh apic test -C apic-demo --format junit --output report.xml head -2 report.xml rm report.xml ``` ``` <?xml version="1.0" encoding="UTF-8"?> <testsuites name="apic" tests="14" skipped="0" failures="0" errors="0" time="0.336821"> ``` Exit codes follow the rest of apic: `0` every scenario passed, `1` a failure or an undefined step, `2` a definition problem, `3` a server that could not be reached. The same suite is one MCP call away for an agent: `run_features` returns the summary and the failures, and `apic test --steps --json` gives an agent the vocabulary to write a feature with. ## Checkpoint Every feature in the project passes, yours included: <!-- learn --> ```sh apic test -C apic-demo --format progress | grep scenarios ``` ``` 14 scenarios (14 passed) ``` (The count includes the features you wrote; `apic test -C apic-demo --json | jq '[.[] | .elements[] | .steps[] | .result.status] | all(. == "passed")'` prints `true`.) ## Exercise Write a feature for the jobs resource: submit a job, then wait until it is done. `jobs.http` already declares the phrases, and `wait-for-job` carries the `# @retry` from lesson 4, so the waiting is one step. <details> <summary>Solution</summary> <!-- learn --> ```sh cat > apic-demo/features/jobs.feature <<'EOF' Feature: Background jobs Background: Given I am logged in Scenario: A job is done after a couple of polls When a job is submitted Then the response status is 202 And the response body "$.state" is "queued" When I wait for the job Then the response body "$.state" is "done" EOF apic test features/jobs.feature -C apic-demo | tail -3 ``` ``` 1 scenarios (1 passed) 6 steps (6 passed) 505.232235ms ``` `a job is submitted` runs `create-job`, which captures `jobId`. `I wait for the job` runs `wait-for-job`, whose `# @retry 5 500ms` sends it until `state == done`; the step takes as long as the retries take and passes once they do. The half second in the timing is the one wait between the first and second attempt. </details> ## Going further - [Testing with Gherkin](https://apic.sh/testing/), every step and option - [Describe behaviour, then test it](https://apic.sh/cookbook/#describe-behaviour-then-test-it) - [`apic test`](https://apic.sh/cli/#apic-test) in the reference <details> <summary>Episode script</summary> **Length.** 12 minutes. **Cold open (0:00).** `todos.feature` on screen, then `apic test` passing. "Eight scenarios, forty-seven steps, and not one line of step code. Here is how." **Talking points.** 1. The shipped suite, and the first scenario read aloud. 2. `--steps`: the two halves of the language. 3. The first feature: three lines. 4. Phrases on requests, `with:` tables, `contains:` doc strings, a `Scenario Outline`. 5. Tags and a smoke expression. 6. Isolation: the scenario that skipped login, and `--use-session`. 7. An undefined step, and why there is no step code to add. 8. Reports, exit codes, the `run_features` MCP tool in one breath. 9. Checkpoint and the jobs exercise, with `# @retry` doing the waiting. **Shot list.** One terminal, 100x30, font size 16, the feature file open in an editor split for steps 3 to 5. `docs/learn/tapes/07.tape` reproduces the terminal parts. **Chapters.** `0:00 No step code` · `0:50 The shipped suite` · `2:00 The vocabulary` · `3:00 Your first feature` · `4:00 Phrases, tables, doc strings, outlines` · `6:30 Tags` · `7:20 Every scenario starts clean` · `8:40 Undefined steps` · `9:40 Reports` · `10:40 Checkpoint and exercise`. **Description.** From the [episode template](https://github.com/hungovercoders/apic/blob/main/docs/learn/_episode-template.md). </details> --- # Lesson 8: CI without leaking secrets URL: https://apic.sh/learn/08-ci/ Lesson 8: run a smoke flow and a feature suite in GitHub Actions with the secret from the environment, --redact and a JUnit report. **Goal.** Run a smoke flow and a feature suite in GitHub Actions, with the secret coming from the environment and a log that is safe to keep. ## You will need - apic installed ([lesson 1](https://apic.sh/learn/01-first-request/)) - `apic demo` running in another terminal, or start it now: ```sh apic demo --out apic-demo ``` - A GitHub repository you can push a workflow to, for the last step. Every command in the workflow is also run here, locally, so the lesson works without one. ## Steps ### 1. What the job has to do A CI job for an API project has four jobs of its own: install apic, check the files before sending anything, run the requests, and report. And it has one rule: no secret in the workflow file, on the runner's disk, or in the log. apic was built to make that the easy path: - `APIC_VAR_<name>` supplies a variable from the environment, so a secret travels from `${{ secrets.… }}` to the request without touching a file. - `--redact` masks header values, bodies, query values and captured values in the output, so the log can be stored. - `--json` and the exit codes give the step something to act on. - Nothing prompts, ever, so a job never hangs waiting for input. ### 2. Validate as the pull-request gate `apic validate` parses every file and reports problems without sending a request, which makes it a cheap first step. With `--format github`, each finding becomes an annotation on the pull request at the exact line and column: <!-- learn --> ```sh apic validate -C apic-demo --format github ``` ``` ✓ 4 files, 24 requests, no problems ``` On a project with a problem the line is a workflow command, which Actions turns into an annotation: ``` ::error file=todos.http,line=3,col=11,endLine=3,endColumn=17,title=apic%3A unknown-selector::assert "stauts == 200": unknown selector "stauts" ``` Errors exit `2` and fail the step; warnings alone do not. ### 3. Run with the secret from the environment The demo's password lives in `http-client.private.env.json`, which is gitignored in a real project and so does not exist on the runner. In CI it arrives as an environment variable instead, and `--redact` keeps it out of the log: <!-- learn --> ```sh APIC_VAR_password=s3cret apic run login whoami -C apic-demo --json --redact ``` ``` {"ok":true,"request":{"name":"login","file":"auth.http","line":9,"method":"POST","url":"http://localhost:8089/auth/login","headers":{"Content-Type":"***"},"body":"***"},"captures":{"token":"***"},"response":{"status":200,"status_text":"OK","headers":{"content-length":"***","content-type":"***","date":"***"},"body":"***","duration_ms":1,"size":30,"proto":"HTTP/1.1","timings":{"dns_ms":0,"connect_ms":0,"tls_ms":0,"ttfb_ms":1,"total_ms":1,"reused":false}},"asserts":[{"expr":"status == ***","pass":true,"actual":"***","expected":"***"}]} {"ok":true,"request":{"name":"whoami","file":"auth.http","line":20,"method":"GET","url":"http://localhost:8089/me","headers":{"Authorization":"***"}},"response":{"status":200,"status_text":"OK","headers":{"content-length":"***","content-type":"***","date":"***"},"body":"***","duration_ms":0,"size":30,"proto":"HTTP/1.1","timings":{"dns_ms":0,"connect_ms":0,"tls_ms":0,"ttfb_ms":0,"total_ms":0,"reused":true}},"asserts":[{"expr":"status == ***","pass":true,"actual":"***","expected":"***"},{"expr":"body.$.email endsWith ***","pass":true,"actual":"***","expected":"***"}]} ``` What survives redaction is exactly what a pipeline needs: `ok`, the status, the timing, and whether each assertion passed. What does not survive is anything a person could copy out of the log. `APIC_VAR_password` beat the private file because the shell sits above every file in the [precedence order](https://apic.sh/learn/02-variables-and-environments/#6-the-order). Prove the secret really came from the environment by passing a wrong one: <!-- learn --> ```sh APIC_VAR_password=wrong apic run login -C apic-demo --json --redact || echo "exit $?" ``` ``` {"ok":false,"errors":["capture token: nothing at body.$.access_token"],"request":{…},"response":{"status":401,…},"asserts":[{"expr":"status == ***","pass":false,"actual":"***","expected":"***"}]} exit 1 ``` Exit `1`, and the step fails. A network error would be `3`, a missing variable `2`; the [exit codes](https://apic.sh/cli/#exit-codes) are the contract. ### 4. The feature suite as a test report `apic test` writes JUnit XML, the format every CI dashboard reads, and `--redact` applies to it too: <!-- learn --> ```sh apic test -C apic-demo --format junit --output report.xml --redact head -2 report.xml rm report.xml ``` ``` <?xml version="1.0" encoding="UTF-8"?> <testsuites name="apic" tests="15" skipped="0" failures="0" errors="0" time="0.837017"> ``` (Fifteen with the features from lesson 7 and its exercise; eight from the shipped file alone.) A reporter action turns that file into a check with one line per scenario on the pull request. ### 5. The workflow Everything above, in one file. It installs a pinned apic with the `setup-apic` action, starts the demo API inside the job so the workflow is self-contained, and runs the three steps with the secret from `${{ secrets.API_PASSWORD }}`: ```yaml # .github/workflows/api.yml name: API on: [push, pull_request] permissions: contents: read checks: write # for the test reporter jobs: api: runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 - uses: hungovercoders/apic/setup-apic@v0 with: version: v0.2.0 # the release you tested against; "latest" floats # The API under test. A real project points --env at a deployed # environment instead and drops these two steps. - run: apic demo --out apic-demo --port 8089 & - run: until curl -fs http://localhost:8089/health > /dev/null; do sleep 0.2; done - name: Validate the request files run: apic validate -C apic-demo --format github - name: Smoke flow run: apic run login whoami todos.http -C apic-demo --keep-going --json --redact --no-session env: APIC_VAR_password: ${{ secrets.API_PASSWORD }} - name: Feature suite if: always() run: apic test -C apic-demo --format junit --output report.xml --redact env: APIC_VAR_password: ${{ secrets.API_PASSWORD }} - uses: dorny/test-reporter@v1 if: always() with: name: API features path: report.xml reporter: java-junit ``` To try it, copy the file into any repository, add a repository secret named `API_PASSWORD` with the value `s3cret`, and push. The smoke step goes red on the deliberate `not-found` failure in `todos.http`, which is the point: a failed assertion fails the build, and the log shows which one without showing a single value. Delete `todos.http` from the targets, or the `not-found` request, and it goes green. Four things to notice in the file. The demo is started in the background with `&` and the job waits for `/health` before using it. The password never appears: it goes from a repository secret to an environment variable to the request. `--no-session` keeps the token `login` captures off the runner's disk, because it neither reads nor writes `.apic/session.json`; captures still pass between the requests of one invocation, so `whoami` and the flow get it. And `if: always()` runs the suite and the reporter even when the smoke step failed, so one broken request does not hide the rest of the report. Where the runner is not GitHub Actions, `install.sh` does what the action does: ```sh curl -fsSL https://raw.githubusercontent.com/hungovercoders/apic/main/install.sh | sh ``` ## Checkpoint The redacted, JSON, environment-fed run from step 3 is the whole lesson in one line. It prints `"ok":true` for both requests and nothing a person could reuse: <!-- learn --> ```sh APIC_VAR_password=s3cret apic run login whoami -C apic-demo --json --redact | grep -c '"ok":true' ``` ``` 2 ``` ## Exercise Run the smoke flow against two environments in one workflow, with a matrix. Lesson 2's exercise gave the demo a `staging` environment; if you skipped it, add one now with the same `baseUrl`, `user` set to `alice`, and a `staging` block in the private file. <details> <summary>Solution</summary> In the workflow, the smoke step becomes a matrix job: ```yaml jobs: smoke: strategy: matrix: env: [local, staging] runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 - uses: hungovercoders/apic/setup-apic@v0 with: version: v0.2.0 - run: apic demo --out apic-demo --port 8089 & - run: until curl -fs http://localhost:8089/health > /dev/null; do sleep 0.2; done # The demo writes only `local`; give the job a `staging` that # shares the same API, as lesson 2 did by hand. - run: | printf '{ "$shared": { "baseUrl": "http://localhost:8089" }, "local": {}, "staging": {} }' > apic-demo/http-client.env.json - run: apic run login whoami -C apic-demo --env ${{ matrix.env }} --json --redact --no-session env: APIC_VAR_password: ${{ secrets.API_PASSWORD }} ``` Locally, the same loop: <!-- learn --> ```sh for env in local staging; do APIC_VAR_password=s3cret apic run login whoami -C apic-demo --env "$env" --json --redact | grep -c '"ok":true' done ``` ``` 2 2 ``` The password is the same secret for both here; a real project uses one secret per environment (`secrets.STAGING_PASSWORD`) or a GitHub environment per matrix row, and `--env` picks the `baseUrl`. </details> ## Going further - [A smoke test in CI that never leaks secrets](https://apic.sh/cookbook/#a-smoke-test-in-ci-that-never-leaks-secrets) in the cookbook - [Reports and CI](https://apic.sh/testing/#reports-and-ci) in the testing guide - [Verifying a release](https://apic.sh/verifying/), for the paranoid runner - [`apic validate`](https://apic.sh/cli/#apic-validate) formats, including SARIF for code scanning <details> <summary>Episode script</summary> **Length.** 10 minutes, mostly a workflow file and the Actions UI. **Cold open (0:00).** A CI log with a bearer token in it, blurred. "This is how most API tests leak. Ten minutes to a pipeline that cannot." **Talking points.** 1. The four jobs of a CI job and the one rule. 2. `validate --format github`: an annotation on a pull request, live. 3. The redacted run: what survives, what does not; the wrong password and exit 1. 4. The JUnit report and the reporter check. 5. The workflow file, top to bottom, then the Actions run: red on `not-found`, the annotation, the report. Remove the request, green. 6. `install.sh` for any other CI. 7. Checkpoint, then the matrix exercise. **Shot list.** The workflow file in an editor; the GitHub Actions run page and the pull-request checks tab, prerecorded. One terminal for steps 2 to 4, recorded by `docs/learn/tapes/08.tape`. **Chapters.** `0:00 The leak` · `0:40 Four jobs, one rule` · `1:30 Validate as the gate` · `2:40 The secret from the environment` · `4:40 The JUnit report` · `5:40 The workflow` · `8:20 Other CI` · `8:50 Checkpoint and exercise`. **Description.** From the [episode template](https://github.com/hungovercoders/apic/blob/main/docs/learn/_episode-template.md). </details> --- # Lesson 9: From OpenAPI to a project, and back to curl URL: https://apic.sh/learn/09-import-export/ Lesson 9: turn an OpenAPI document, a Postman collection or a curl command into a project, run the draft against a mock of the document, tidy it, and export a curl command back out. **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 - apic installed ([lesson 1](https://apic.sh/learn/01-first-request/)) - `apic demo` running in another terminal, or start it now: ```sh 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 schemas with examples for what goes in and what comes back (the responses matter in step 3, when the document itself is the server): <!-- learn --> ```sh 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: <!-- learn --> ```sh 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: <!-- learn --> ```sh 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 `validate` and `list` work on a draft exactly as on a finished project: <!-- learn --> ```sh 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: <!-- learn --> ```sh 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](https://apic.sh/learn/02-variables-and-environments/): <!-- learn --> ```sh 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 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: <!-- learn --> ```sh 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](https://apic.sh/learn/02-variables-and-environments/)), so pointing one run at the mock is one flag: <!-- learn --> ```sh 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: <!-- learn --> ```sh 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 ``` <!-- learn --> ```sh 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: <!-- learn --> ```sh kill "$(cat mock.pid)" ``` ### 4. Tidy the draft until it runs green Now the todos, against the demo again: <!-- learn --> ```sh 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: <!-- learn --> ```sh 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: <!-- learn --> ```sh 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](https://apic.sh/learn/03-capture-session-flows/): list, create, fetch what was created. Run it: <!-- learn --> ```sh 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. ### 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: <!-- learn --> ```sh 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: <!-- learn --> ```sh 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: <!-- learn --> ```sh 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 ``` ### 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: <!-- learn --> ```sh 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: <!-- learn --> ```sh 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. ### 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: <!-- learn --> ```sh 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: <!-- learn --> ```sh 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: <!-- learn --> ```sh 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: <!-- learn --> ```sh 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: <!-- learn --> ```sh 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 Import a public OpenAPI document of your choice and get one request green. The [Swagger Petstore](https://petstore3.swagger.io/) publishes its document at `https://petstore3.swagger.io/api/v3/openapi.json`, and its `GET /store/inventory` needs no account. <details> <summary>Solution</summary> ```sh 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. </details> ## Going further - [`apic import`](https://apic.sh/cli/#apic-import), every mapping for OpenAPI, Postman and curl, and what each importer reports as unsupported - [`apic mock`](https://apic.sh/cli/#apic-mock), how a response is chosen and built, the `Prefer` header, and what the mock deliberately does not do - [`apic curl`](https://apic.sh/cli/#apic-curl) and the [auth](https://apic.sh/auth/) mapping onto curl's own flags - [Comparison](https://apic.sh/comparison/) with Postman, Bruno, Hurl and httpyac, including what apic does instead of scripting <details> <summary>Episode script</summary> **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](https://github.com/hungovercoders/apic/blob/main/docs/learn/_episode-template.md). </details> --- # Lesson 10: Agents and MCP URL: https://apic.sh/learn/10-agents/ Lesson 10: let an AI agent discover, describe and run your requests through the shell contract, --json and the MCP server, without handing it a secret. **Goal.** Let an AI agent discover, describe and run your requests, from the shell through the JSON contract and over MCP as tools, without ever handing it a secret. ## You will need - apic installed ([lesson 1](https://apic.sh/learn/01-first-request/)) - `apic demo` running in another terminal, or start it now: ```sh apic demo --out apic-demo ``` - `jq`, because that is what an agent reaches for too - For step 5 only: an MCP client such as Claude Code, Cursor or Windsurf. Every other step works with a plain shell, and so does the checkpoint. ## Steps ### 1. The contract an agent reads An agent that can run shell commands needs three things from a tool: output it can parse, exit codes it can branch on, and no prompts that would leave it hanging. apic gives all three to every command, and the [agents guide](https://apic.sh/agents/) has the paragraph to paste into your project's `AGENTS.md` or `CLAUDE.md`. The short version: ```markdown Requests live in `*.http` and are run with `apic`. - `apic list --json`: every request with id, method, URL and description - `apic describe <id> --json`: the variables it needs and whether it is ready - `apic run <id> --json`: send it; one JSON object with ok, request, response, captures, asserts - `apic validate --json`: check every file before running anything Exit codes: 0 ok, 1 assertion failed, 2 usage/parse/missing variable, 3 network. Captured values persist, so run `login` once; a missing variable names the request that captures it. ``` That is the whole briefing. Watch it work by running the commands the way an agent would, with `jq` picking the fields it cares about: <!-- learn --> ```sh apic list -C apic-demo --json | jq -r '.requests[] | "\(.id)\t\(.method) \(.url)"' | head -5 ``` ``` login POST {{baseUrl}}/auth/login whoami GET {{baseUrl}}/me basic-auth GET {{baseUrl}}/basic-auth/{{user}}/{{password}} oauth2-token GET {{baseUrl}}/me api-key GET {{baseUrl}}/keyed ``` ### 2. What the agent sees when something is missing The moment the design shows itself is a request that is not ready yet. Start from an empty session, so nothing has been captured: <!-- learn --> ```sh apic session clear -C apic-demo apic describe get-todo -C apic-demo --json | jq -c '{ready, missing: [.variables[] | select(.missing) | {name, captured_by}]}' ``` ``` {"ready":false,"missing":[{"name":"todoId","captured_by":"create-todo"},{"name":"token","captured_by":"login"},{"name":"todoTitle","captured_by":"create-todo"}]} ``` `describe` does not just say what is missing; it says which request produces each value. An agent that runs the request anyway gets the same answer as JSON on stdout, the human message on stderr, and exit code 2: <!-- learn --> ```sh apic run get-todo -C apic-demo --json 2>/dev/null | jq -c '{ok, errors}' apic run get-todo -C apic-demo --json >/dev/null 2>&1 || echo "exit $?" ``` ``` {"ok":false,"errors":["todos.http:42: missing variables\n {{todoId}}: it is captured by request \"create-todo\"; run `apic run create-todo` first, or pass --var todoId=...\n {{token}}: it is captured by request \"login\"; run `apic run login` first, or pass --var token=..."]} exit 2 ``` Every error apic can produce is written for that reader: what is wrong, what to run, or what to pass. So the agent runs what it was told to, and reads the captures out of the answer: <!-- learn --> ```sh apic run login -C apic-demo --json | jq -c '{ok, captures}' apic run create-todo -C apic-demo --json --var title="From an agent" | jq -c '{ok, status: .response.status, captures}' apic run get-todo -C apic-demo --json | jq -c '{ok, body: .response.body}' ``` ``` {"ok":true,"captures":{"token":"mock-token"}} {"ok":true,"status":201,"captures":{"todoId":"3","todoTitle":"From an agent"}} {"ok":true,"body":{"id":"3","title":"From an agent","done":false}} ``` `response.body` is parsed JSON when the response is JSON, so the agent chains values without string handling (the id is `3` on a fresh demo, higher if you created todos in earlier lessons), and the captures persist, so it logs in once per session rather than before every call. ### 3. `# @ref` takes even that step away `whoami` declares `# @ref login` ([lesson 3](https://apic.sh/learn/03-capture-session-flows/)), so the agent does not need to know about the dependency at all: <!-- learn --> ```sh apic session clear -C apic-demo apic describe whoami -C apic-demo --json | jq -c '{ready, refs, token: [.variables[] | select(.name == "token") | {missing, captured_by, ref_runs}]}' apic run whoami -C apic-demo --json | jq -c '{name: .request.name, ok, status: .response.status}' ``` ``` {"ready":true,"refs":["login"],"token":[{"missing":true,"captured_by":"login","ref_runs":true}]} {"name":"login","ok":true,"status":200} {"name":"whoami","ok":true,"status":200} ``` `ready` is true although the token is missing, because `ref_runs` says the dependency will handle it, and the run prints one object per request that was sent, `login` first. An agent reading NDJSON sees exactly what happened. ### 4. A session, condensed Give an agent the demo project and the briefing from step 1, and ask it to "mark the todo called Buy milk as done". A typical session, with the tool calls shortened to what matters: ```console $ apic list --json | jq -r '.requests[] | select(.file == "todos.http") | .id' list-todos … update-todo $ apic describe update-todo --json | jq '{ready, missing: [.variables[] | select(.missing) | .captured_by]}' {"ready": false, "missing": ["create-todo", "login"]} $ apic run list-todos --json | jq 'first(.response.body[] | select(.title == "Buy milk") | .id)' "1" $ apic run update-todo --json --var todoId=1 | jq '{ok, done: .response.body.done}' {"ok": true, "done": true} ``` Notice what the agent did not have to do: read the `.http` files, guess a URL, or ask you for a token. It found the request by name, learned what it needed, got the id from a listing rather than creating a new todo, and passed it with `--var` because the value it wanted was not the one `create-todo` would have captured. Every step was a documented command with a documented shape. ### 5. Over MCP The Model Context Protocol is the other door: the same project as tools an MCP client calls directly, with no shell in between. Register the server once: ```sh # Claude Code claude mcp add api -- apic mcp --dir ./apic-demo --env local ``` ```json // Cursor (.cursor/mcp.json), Windsurf, and any other MCP client {"mcpServers": {"api": {"command": "apic", "args": ["mcp", "--dir", "./apic-demo", "--env", "local"]}}} ``` The client then sees nine tools: | Tool | What it does | |---|---| | `list_requests` | ids, methods, URL templates, descriptions, captures, asserts | | `describe_request {name}` | variables and sources, the `ready` flag, the refs | | `run_request {name, vars?}` | send one request; the same JSON as `apic run --json`, with `ran_first` for `# @ref` | | `run_file {file, keep_going?}` | run a file as a flow | | `run_features {paths?, tags?}` | run the Gherkin features; pass/fail counts and the failing steps | | `list_environments` | environments and the variables in effect, secrets masked | | `clear_session {all?}` | forget captured values and cookies | | `validate_project {}` | check every `.http` file, with file, line, column and code, without sending anything | | `curl_request {name, lang?, raw?}` | the equivalent curl command, or HTTPie, PowerShell, Python, JavaScript or Go with `lang`, masked unless `raw` | and every `.http` file as a resource it can read, so it can look at a request's definition before calling it, or write a new one in the same style. The server speaks JSON-RPC over stdin and stdout, which means you can talk to it from a shell as well. Three lines, the MCP handshake and one call, list the tools: <!-- learn --> ```sh (printf '%s\n' \ '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-03-26","capabilities":{},"clientInfo":{"name":"lesson","version":"0"}}}' \ '{"jsonrpc":"2.0","method":"notifications/initialized"}' \ '{"jsonrpc":"2.0","id":2,"method":"tools/list"}'; sleep 1) \ | apic mcp --dir apic-demo 2>/dev/null | jq -r 'select(.id == 2) | .result.tools[].name' ``` ``` clear_session curl_request describe_request list_environments list_requests run_features run_file run_request validate_project ``` ### 6. What the agent can never read The resources are the `.http` files and nothing else. The private env file, `.env` and `.apic/session.json` sit in the same directory, and a read of any of them is refused: <!-- learn --> ```sh (printf '%s\n' \ '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-03-26","capabilities":{},"clientInfo":{"name":"lesson","version":"0"}}}' \ '{"jsonrpc":"2.0","method":"notifications/initialized"}' \ "{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"resources/read\",\"params\":{\"uri\":\"file://$PWD/apic-demo/http-client.private.env.json\"}}"; sleep 1) \ | apic mcp --dir apic-demo 2>/dev/null | jq -c 'select(.id == 3) | .error.message' ``` ``` "Resource not found" ``` The same line holds everywhere an agent looks: `list_environments` masks secrets as `apic env` does, `run_request` shows sensitive request headers as `***`, and the tokens `# @auth oauth2` and `exec` cache in the session are described (`$oauth2:… = token, expires in 1h0m0s`), never printed. What the agent does get is real URLs, bodies and captured values, the token that `login` captured included, because it needs them to chain calls: step 2 printed `mock-token` for that reason. When the output is going into a stored log rather than to an agent, add `--redact`, which masks those too; a redacted run is for logs, not for chaining. ### 7. The agent as an author Because the format is plain text, an agent can add requests, and `validate --json` (or the `validate_project` tool) tells it where it went wrong with a line and a column: <!-- learn --> ```sh mkdir -p agent-draft printf '### Health\n# @name health\n# @assert stauts == 200\nGET http://localhost:8089/health\n' > agent-draft/health.http apic validate -C agent-draft --json | jq -c '.diagnostics[] | {path, line, column, code, message}' ``` ``` {"path":"health.http","line":3,"column":11,"code":"unknown-selector","message":"assert \"stauts == 200\": unknown selector \"stauts\""} ``` For features, `apic test --steps --json` lists every step the agent may use, so it writes scenarios from a vocabulary that exists rather than one it imagines: <!-- learn --> ```sh apic test --steps -C apic-demo --json | jq -r '.[].pattern' | head -4 ``` ``` the environment is "<name>" the variable "<name>" is "<value>" the variables: (table name | value) I run "<request>" ``` and `run_features` over MCP (or `apic test --json` from the shell) hands back the failing steps with their errors, which is what the agent needs to fix the request or the scenario. ### 8. The briefing as a skill The paragraph in step 1 costs a few hundred tokens on every turn, whether or not the task touches the API. A skill is the same briefing loaded on demand: the agent sees one line saying when it applies, and reads the rest only when a task involves `.http` files or an API call. The binary carries one, in the [Agent Skills](https://agentskills.io) format that Claude Code, Codex, Cursor and the others read, and installs it into the project: <!-- learn --> ```sh apic skill install -C apic-demo grep '^## ' apic-demo/.claude/skills/apic/SKILL.md ``` ``` wrote apic-demo/.claude/skills/apic/SKILL.md wrote apic-demo/.claude/skills/apic/references/cheatsheet.md wrote apic-demo/.agents/skills/apic/SKILL.md wrote apic-demo/.agents/skills/apic/references/cheatsheet.md ## Running requests ## When a command fails ## Writing or changing requests ## Testing an API ## Over MCP instead of the shell ## Designing or securing the API itself ``` That last section points at two more skills the binary carries, `api-design` (how to design the API the requests call, each rule proved by a request or an `apic mock`) and `api-security` (how to keep it safe, with the OWASP API Security Top 10 as checks). They are opinions about your API rather than about apic, so they are an opt-in: `apic skill install --all` adds them to the project, or `apic skill install --user --all` to your home directory for every project. Two copies, one per convention, and the same five things this lesson walked through: the validate, list, describe, run order; the error codes to branch on; how to write a request and where secrets belong; when to reach for `apic test`; and the MCP tools, which the skill tells the agent to prefer when they exist. `references/cheatsheet.md` is the [cheat sheet](https://apic.sh/cheatsheet/) with absolute links, generated from the binary so the two cannot drift. Commit the directories. `apic init` writes them for a new project, `apic skill` prints the briefing for an agent that can only run commands, and `npx skills add hungovercoders/apic` fetches the same files from the repository for the agents that CLI finds. ## Checkpoint The MCP server answers a `tools/list` over stdio with the nine tools: <!-- learn --> ```sh (printf '%s\n' \ '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-03-26","capabilities":{},"clientInfo":{"name":"lesson","version":"0"}}}' \ '{"jsonrpc":"2.0","method":"notifications/initialized"}' \ '{"jsonrpc":"2.0","id":2,"method":"tools/list"}'; sleep 1) \ | apic mcp --dir apic-demo 2>/dev/null | jq 'select(.id == 2) | .result.tools | length' ``` ``` 9 ``` ## Exercise Ask an agent, over MCP or the shell, to add pagination assertions to `list-todos` in the demo project and make them pass. Give it only the briefing from step 1 and the request's name. <details> <summary>Solution</summary> A good agent reads `todos.http` (as a resource, or with `cat`), runs `list-open-todos` to see what the API returns, notices the `X-Total-Count` and `X-Page` headers, and adds: ```http # @assert header.x-total-count >= 1 # @assert body.$.# <= 20 ``` (20 is the API's default page size, since `list-todos` sends no `limit`), then runs `apic validate --json` and `apic run list-todos --json` and reports the `asserts` array. The demo's `list-open-todos` already carries these, so the agent can also be judged on whether it looked next door first. If it wrote an assertion with a selector that does not exist, `validate` told it the column before the request was ever sent. </details> ## Going further - [Using apic from an AI agent](https://apic.sh/agents/): the full briefing, the `--json` shape, and the MCP tool reference - [For agents](https://apic.sh/testing/#for-agents) in the testing guide: `run_features` and the steps vocabulary - [`apic mcp`](https://apic.sh/cli/#apic-mcp) in the reference <details> <summary>Episode script</summary> **Length.** 12 minutes; includes a real agent session, sped up. **Cold open (0:00).** An agent stuck: a chat transcript where it guesses a URL, gets a 401, and asks the user for a token. "The tool was never built for it. Here is one that was." **Talking points.** 1. The three things an agent needs and the one-paragraph briefing. 2. `describe` on a request that is not ready: `captured_by`; the run that fails with a JSON object and exit 2; the agent doing what the error said. 3. `# @ref`: `ready: true` with `ref_runs`, two objects from one run. 4. The recorded session with Claude Code, sped up: list, describe, list-todos for the id, update-todo with `--var`. 5. `claude mcp add`, the nine tools, a request as a resource; the stdio handshake from a shell. 6. The refused read of the private env file; masking versus `--redact`. 7. The agent writing a request: `validate --json` with the column; `--steps --json` for features. 8. The skill: the same briefing on demand, `apic skill install`, the five sections, and the cheat sheet that cannot drift. 9. Checkpoint, then the pagination exercise. **Shot list.** A terminal for steps 1 to 3 and 5 to 8; the agent session prerecorded in Claude Code, at 2x, with the tool calls expanded. `docs/learn/tapes/10.tape` records the terminal parts. **Chapters.** `0:00 The stuck agent` · `0:40 The briefing` · `1:40 Not ready, and what to do` · `3:30 # @ref` · `4:20 A real session` · `6:40 MCP` · `8:40 What it cannot read` · `9:40 The agent as author` · `10:30 The skill` · `11:20 Checkpoint and exercise`. **Description.** From the [episode template](https://github.com/hungovercoders/apic/blob/main/docs/learn/_episode-template.md). </details> --- # Lesson 11: Real APIs and the Taskfile front door URL: https://apic.sh/learn/11-real-apis/ Lesson 11: run the three example projects against real services, keep credentials out of git, and make task the way the team runs it. **Goal.** Run apic against three real services with the three example projects, keep the credentials out of git, and make `task` the way your team runs all of it. ## You will need - apic installed ([lesson 1](https://apic.sh/learn/01-first-request/)) and a network connection: this lesson leaves the demo API behind - The repository's `examples/` directory. Clone it, or download it: ```sh git clone --depth 1 https://github.com/hungovercoders/apic cd apic ``` - For step 2, a GitHub account; for step 3, a Spotify account. Step 1 needs neither. - [Task](https://taskfile.dev) for step 5, and `jq` for the checkpoint. ## Steps ### 1. httpbin: no account, two kinds of auth [httpbin.org](https://httpbin.org) is a public echo service: it answers with what you sent, which makes it a good first real target. The `httpbin` example has two environments, and `dev` points at it (`local` points at `apic demo`, for the requests that both serve): ```sh apic list -C examples/httpbin apic run auth.http -C examples/httpbin --env dev ``` ``` ✓ login 200 312 ms ✓ whoami 200 298 ms ✓ basic-auth 200 301 ms ✓ bearer-auth 200 295 ms 4 passed · 4 requests · 1206 ms ``` The timings are the network's, and the first request is the interesting one. httpbin has no login, so `login` posts a token it made up itself, `demo-{{$uuid}}`, and captures it back out of the echo: ```http ### Log in and keep the token # @name login # @assert status == 200 # @capture token = body.$.json.token POST {{baseUrl}}/post Content-Type: application/json {"user": "{{user}}", "password": "{{password}}", "token": "demo-{{$uuid}}"} ``` `whoami` then sends it to `/bearer`, which accepts any bearer token and answers `authenticated: true`, and `basic-auth` lets `# @auth basic` encode the credentials for `/basic-auth/alice/s3cret`. Nothing here is special to httpbin; it is the same capture and auth from lessons 3 and 6 on the open internet. The second file has a deliberate expected 404: ```sh apic run users.http -C examples/httpbin --env dev --keep-going ``` ``` ✓ get-user 200 305 ms ✓ create-user 200 299 ms ✓ not-found 404 290 ms 3 passed · 3 requests · 894 ms ``` `not-found` asserts `status == 404`, so it passes: an assertion is about what you expect, not about 2xx. The password for the `basic-auth` request is in the example's `http-client.private.env.json`, and that file is committed on purpose, which is the subject of the next step. ### 2. GitHub: a personal access token in the private file The `github` example reads one repo through the REST API with a bearer token. Its private file ships with a placeholder: ```sh cat examples/github/http-client.private.env.json ``` ```json { "dev": { "token": "ghp_replace-with-your-own-token" } } ``` Two things about that file. The repository's root `.gitignore` ignores every `http-client.private.env.json`, then re-includes the ones under `examples/` so the placeholders can be committed; in your own project the ignore line stands alone, and `apic init` writes it for you. And apic writes the file with mode `0600` when it creates one, so nobody else on the machine reads it either. Make a token: on GitHub, **Settings → Developer settings → Personal access tokens → Fine-grained tokens**, with no permissions at all. The three requests read public data; the token only raises the rate limit and identifies you to `/user`. If you have the `gh` CLI, `gh auth token` prints one you already have. Put it in the file, then: ```sh apic run repo.http -C examples/github ``` ``` ✓ whoami 200 180 ms ✓ get-repo 200 160 ms ✓ list-issues 200 210 ms 3 passed · 3 requests · 550 ms ``` The `env: dev` in `apic.yaml` means no `--env` is needed. The example also carries a feature file, and `apic test` runs it against the same requests: ```sh apic test -C examples/github ``` ``` 3 scenarios (3 passed) 8 steps (8 passed) 612.5ms ``` ### 3. Spotify: OAuth2 client credentials The `spotify` example is the OAuth2 flow from [lesson 6](https://apic.sh/learn/06-authentication/) against a real authorization server. Create an app at [developer.spotify.com/dashboard](https://developer.spotify.com/dashboard) (any name, any redirect URI; the client-credentials grant never uses it) and copy its client id and secret into the private file: ```json { "dev": { "clientId": "your-client-id", "clientSecret": "your-client-secret" } } ``` The request declares everything else: ```http ### Search for an artist # @name search-artist # @auth oauth2 tokenUrl={{tokenUrl}} clientId={{clientId}} clientSecret={{clientSecret}} grant=client_credentials clientAuth=basic # @assert status == 200 # @assert body.$.artists.items[0].name exists GET {{baseUrl}}/v1/search ?q=radiohead &type=artist &market={{market}} ``` `clientAuth=basic` is the detail that matters for Spotify: it wants the id and secret in a Basic header on the token request rather than in the form body, and that one word is the difference between a token and a 401. Run the file: ```sh apic run search.http -C examples/spotify ``` ``` ✓ search-artist 200 420 ms ✓ new-releases 200 260 ms 2 passed · 2 requests · 680 ms ``` The token was fetched once, before the first request, and cached in the session for its lifetime; `apic session -C examples/spotify` shows it described (`$oauth2:… = token, expires in 1h0m0s`), never printed. The second request reused it. When you show this on a screen or paste it into a ticket, add `--redact`: the URLs stay, and every header value, body and captured value becomes `***`. ### 4. What each example needs, in one place | Project | Environment | Private file holds | Where it comes from | |---|---|---|---| | `examples/httpbin` | `dev` (httpbin.org), `local` | `password` | Committed; any value works | | `examples/github` | `dev` | `token` | A fine-grained PAT with no permissions, or `gh auth token` | | `examples/spotify` | `dev` | `clientId`, `clientSecret` | An app in the Spotify developer dashboard | Every example is checked by CI with `apic validate` and `apic fmt --check` but never run there: real credentials do not belong in CI for a sample. Your own project is different, and [lesson 8](https://apic.sh/learn/08-ci/) is how its secrets travel. ### 5. The Taskfile front door Once the requests are files, the question is how a team runs them without each person remembering flags. The repository's own `Taskfile.yml` answers it for the examples: ```sh task example:github task example:spotify ``` The pattern behind those tasks is short, and the [Taskfile guide](https://apic.sh/taskfile/) has the long version. A project's `Taskfile.yml` looks like this: ```yaml version: "3" vars: ENV: '{{.ENV | default "dev"}}' tasks: api: desc: Run any request, e.g. task api -- get-user --env staging dir: api cmds: - apic run {{.CLI_ARGS}} login: desc: Log in and keep the token for the tasks below dir: api cmds: - apic run login --env {{.ENV}} smoke: desc: Run every request in smoke.http dir: api cmds: - apic run smoke.http --env {{.ENV}} api:check: desc: Validate the request files and run the smoke flow, as CI does dir: api cmds: - apic validate - apic run smoke.http --env {{.ENV}} --json --redact ``` Three details carry the design. `dir: api` on every task puts apic in the same directory each time, so they all share one `.apic/session.json` and `task login` once serves `task smoke` afterwards. `{{.CLI_ARGS}}` makes `task api -- whoami --env dev` behave exactly like `apic run`, so the Taskfile adds a front door without hiding the tool. And `task api:check` is the one command a newcomer or a CI job runs, with the secret arriving through the environment: ```sh APIC_VAR_password="$API_PASSWORD" task api:check ENV=staging ``` Exit codes pass straight through, so a failed assertion fails the task. ## Checkpoint The Spotify flow runs green with your own credentials: ```sh apic run search.http -C examples/spotify --json | jq -s 'map(.ok) | all' ``` ``` true ``` If you skipped Spotify, the GitHub file is the same check: `apic run repo.http -C examples/github --json | jq -s 'map(.ok) | all'`. ## Exercise Add a fourth example project for an API you use, with one flow and one feature. Start it with `apic init`, which writes the config, the env files, the `.gitignore` lines, a first request and the Agent Skill; point it at the demo API first if the real one needs credentials you do not have to hand. <details> <summary>Solution</summary> <!-- learn --> ```sh apic init my-api --base-url http://localhost:8089 --env local apic run ping -C my-api | tail -1 ``` ``` wrote my-api/apic.yaml wrote my-api/http-client.env.json wrote my-api/http-client.private.env.json wrote my-api/api.http wrote my-api/features/smoke.feature wrote my-api/.gitignore wrote my-api/.claude/skills/apic/SKILL.md wrote my-api/.claude/skills/apic/references/cheatsheet.md wrote my-api/.agents/skills/apic/SKILL.md wrote my-api/.agents/skills/apic/references/cheatsheet.md next: cd my-api edit api.http, then: apic list · apic run ping · apic ui ✓ status == 200 ``` `api.http` has `ping` and a `get-thing` that needs an `apiKey` from the private file and an `id`, and `features/smoke.feature` has one scenario on `ping`. Replace `baseUrl` with the real API, rewrite `get-thing` as its first real request, give the flow a second request that uses a capture from the first, and add a scenario for it. `apic validate`, `apic run api.http` and `apic test` are the three checks; when all three pass, the project is ready for a `Taskfile.yml` like the one in step 5. </details> ## Going further - [The example projects](https://github.com/hungovercoders/apic/tree/main/examples), each with a README-level note in its files - [Using apic with Taskfile](https://apic.sh/taskfile/): every pattern, including piping output between tasks and installing apic from a task - [Cookbook](https://apic.sh/cookbook/), for the recipes these examples are simplified from - [Authentication](https://apic.sh/auth/), for the OAuth2 grants and options beyond client credentials <details> <summary>Episode script</summary> **Length.** 10 minutes; live calls with credentials blurred, `--redact` on screen where possible. **Cold open (0:00).** `apic run search.http -C examples/spotify`, two green lines against a real API, no code. "Everything so far was the demo. Now the internet." **Talking points.** 1. httpbin: the made-up token captured out of the echo, `/bearer`, `# @auth basic`; the expected 404. 2. The private file: the placeholder, the `.gitignore` rule and the re-include for the examples, mode 0600. 3. GitHub: a fine-grained token with no permissions; `repo.http`; `apic test` on the feature. 4. Spotify: the app, `clientAuth=basic`, the cached token described in `apic session`, `--redact` on screen. 5. The table of what each example needs; why CI validates but never runs them. 6. The Taskfile: `dir:`, `CLI_ARGS`, `api:check`, the secret through the environment. 7. Checkpoint, then the fourth example exercise with `apic init`. **Shot list.** One terminal for the runs, with the private files opened in an editor and blurred; the GitHub token page and the Spotify dashboard prerecorded. No tape for this lesson (real network). **Chapters.** `0:00 Real APIs` · `0:40 httpbin` · `2:40 The private file` · `3:40 GitHub` · `5:10 Spotify and OAuth2` · `7:00 What each needs` · `7:40 The Taskfile front door` · `9:10 Checkpoint and exercise`. **Description.** From the [episode template](https://github.com/hungovercoders/apic/blob/main/docs/learn/_episode-template.md). </details> --- # Lesson 12: Editors URL: https://apic.sh/learn/12-editors/ Lesson 12: send the same request from VS Code, a JetBrains IDE, Neovim and apic run, and know what each one ignores in the file. **Goal.** Send the same request from VS Code, from a JetBrains IDE, from Neovim and from `apic run`, and know what each one ignores in the file. ## You will need - apic installed ([lesson 1](https://apic.sh/learn/01-first-request/)) - `apic demo` running in another terminal, or start it now: ```sh apic demo --out apic-demo ``` - VS Code for steps 1 and 2. Steps 3 and 4 are for readers of those editors; skip what you do not use. ## Steps ### 1. VS Code with REST Client only Open `apic-demo/` in VS Code with the [REST Client](https://marketplace.visualstudio.com/items?itemName=humao.rest-client) extension installed and open `auth.http`. Above `POST {{baseUrl}}/auth/login` there is a **Send Request** link; click it and the response opens in a panel beside the file. Nothing about the file changed for that to work, and that is the premise of the whole course: a `.http` file is the editor's format, and everything apic adds is a `#` comment the editor does not read. Three things worth noticing while you are there: - `{{baseUrl}}` resolved, because REST Client reads the same `http-client.env.json` (pick the environment with the status-bar item it adds, **No Environment** by default). - `# @name login` is REST Client's own directive, which apic adopted rather than inventing another. Both use it to name a request, and REST Client lets a later request refer to `{{login.response.body.$.access_token}}`, which apic also resolves. - `# @assert`, `# @capture`, `# @ref` and `# @step` are comments to REST Client, and `# @prompt`, which is REST Client's, is ignored by apic: apic never prompts, so the value comes from `--var` or an env file instead. ### 2. The apic extension Install **apic** from the Marketplace or Open VSX (search for `apic`), or from the `.vsix` on the [releases page](https://github.com/hungovercoders/apic/releases?q=vscode). It does not replace REST Client; it layers on top, and the two lenses sit side by side above every request: - **Run** sends the request through apic's runner, so the assertions are evaluated, the captures stored in `.apic/session.json`, and a `# @ref` dependency run first. The request line gets `✓ 200 · 12 ms` or `✗ 404 · 40 ms`, and the response panel shows the body highlighted, each assertion with actual against expected, and the captures. Run `whoami` on a fresh session and watch `login` run before it. <kbd>ctrl+alt+shift+r</kbd> (<kbd>cmd+alt+shift+r</kbd> on a Mac) runs the request under the cursor; REST Client keeps <kbd>ctrl+alt+r</kbd>. - **Describe** shows what `apic describe` shows: every variable, its source, and whether the request is ready. - **Copy as curl** puts the `apic curl` output on the clipboard. - **Run file as flow**, at the top of the file, is `apic run todos.http` with the summary in the panel. Away from the lenses: - The **Problems** panel shows what `apic validate` reports, at the exact span, whenever a request file, `apic.yaml` or an env file is saved. Misspell a selector in an assertion and the squiggle appears with the code linked to the docs; a quick fix offers the nearest known directive for a mistyped one. - The **apic** view in the activity bar lists every request by file with a ready icon from `apic describe`, and the **Session** view shows the captured values (a cached OAuth2 or `exec` token as its description, a captured value as itself, so treat a screen share the way you would treat `apic session`) with **Clear session** above them. - The status bar names the environment in effect; **apic: Select environment** changes it, and every lens passes it as `--env`. - **Format Document** runs `apic fmt` on the file, and with `editor.formatOnSave` the files stay in the canonical order from [lesson 9](https://apic.sh/learn/09-import-export/)'s imports. - Type `# @` above a request and every directive is offered with its shape filled in; type `{{` and the variables of the environment in effect appear with their source, secrets masked. Hover a `{{placeholder}}` to see its value, or which request captures it. - The **Test Explorer** (the beaker in the activity bar) lists `features/todos.feature` with its scenarios. Run one and apic runs it the same way `apic test` does; a failing step shows its message at the line. Open `todos.http` and every `# @step` line says how many scenarios use it. ### 3. JetBrains IDEs IntelliJ, WebStorm, GoLand and the rest ship the HTTP Client, and it opens the same files. Open `apic-demo/` in one, open `auth.http`, and the gutter icon on `login` sends it. It reads `http-client.env.json` and `http-client.private.env.json` too, so one set of environments serves the IDE and apic, and its `SSLConfiguration` block for client certificates is honoured by apic as well ([auth](https://apic.sh/auth/#tls-and-client-certificates)). What the IDE adds that apic does not read is scripting: a `> {% … %}` block after a request runs JavaScript in the IDE. apic has no scripting on purpose, and says so rather than failing. Write a request with a handler and validate it: <!-- learn --> ```sh mkdir -p jetbrains cat > jetbrains/login.http <<'EOF' ### Log in # @name login # @assert status == 200 # @capture token = body.$.access_token POST http://localhost:8089/auth/login Content-Type: application/json {"user": "alice", "password": "s3cret"} > {% client.global.set("token", response.body.access_token); %} EOF apic validate -C jetbrains apic run login -C jetbrains | tail -2 ``` ``` login.http:10:1: warning: ignoring response handler block (apic has no scripting; see https://apic.sh/comparison/) (editor-script) ! 1 file, 1 request, 1 warning ✓ status == 200 ↳ token = mock-token ``` The handler's job in the IDE, keeping the token, is what `# @capture` does for apic in the line above it, so one file serves both: the IDE runs its script and ignores the directive, apic runs the directive and ignores the script. `apic validate` warns so the overlap is visible, and the warning does not fail CI. ### 4. Neovim [kulala.nvim](https://github.com/mistweaverco/kulala.nvim) sends `.http` files from Neovim and reads the same env files. Its companion in the terminal is `apic ui` ([lesson 5](https://apic.sh/learn/05-terminal-ui/)): <kbd>o</kbd> opens the request under the cursor in `$EDITOR`, and the UI reloads the file when you come back, so the editor writes and apic runs, in two panes of the same terminal. ### 5. The same request, four ways Whichever editor sent `login`, the file did not change, and apic runs it the same: <!-- learn --> ```sh apic run login -C apic-demo | tail -2 ``` ``` ✓ status == 200 ↳ token = mock-token ``` The editors give you a click, highlighting and a response pane; apic gives the same file its assertions, its session, CI and an agent. That split is why the format is plain text with comments and nothing else. ## Checkpoint `login` sent from REST Client, from the apic extension and from `apic run`, all with status 200. From the terminal, the last of the three: <!-- learn --> ```sh apic run login -C apic-demo --json | grep -o '"status":200' ``` ``` "status":200 ``` ## Exercise In VS Code with the apic extension, write a new file `editor.http` in the demo project with two requests: `editor-health`, and `me` with `# @ref login` and `# @auth bearer {{token}}`. Run the file as a flow from the CodeLens. <details> <summary>Solution</summary> ```http ### Is the API up? # @name editor-health # @assert status == 200 GET {{baseUrl}}/health ### Who am I # @name me # @ref login # @auth bearer {{token}} # @assert status == 200 # @assert body.$.email endsWith "example.com" GET {{baseUrl}}/me ``` The directive lines are highlighted as you type them; save the file and the Requests view shows `me` with the ready icon, because `# @ref` covers the token. **Run file as flow** at the top runs `editor-health`, then `login` on behalf of `me`, then `me`, and the panel shows three green rows. From the terminal the same file is `apic run editor.http -C apic-demo`. </details> ## Going further - [Editors](https://apic.sh/editors/): what each editor gives you, and how to build the extension from source - [Structure](https://apic.sh/format/#structure) in the format guide, where the `> {% %}` blocks are described, and the [comparison](https://apic.sh/comparison/) with the editors' own features - The extension's own [README](https://github.com/hungovercoders/apic/tree/main/editors/vscode) for every setting <details> <summary>Episode script</summary> **Length.** 10 minutes; three editors on screen. **Cold open (0:00).** The same `auth.http` open in VS Code, a JetBrains IDE and Neovim, tiled; three sends, three 200s. "One file. Same file." **Talking points.** 1. REST Client alone: Send Request, the env picker, `# @name` being theirs, `# @prompt` being theirs and ignored by apic. 2. The apic extension: Run on `whoami` with `login` running first; Describe; Problems from a misspelled selector; the Session view; the environment in the status bar; Format Document. 3. JetBrains: the gutter send; the handler block and the `editor-script` warning; `# @capture` beside the script. 4. Neovim: kulala, and `apic ui` with <kbd>o</kbd>. 5. `apic run login` from the terminal on the untouched file. 6. Checkpoint, then the two-request exercise run as a flow. **Shot list.** Three editor windows prerecorded, each on `auth.http`; one terminal for the validate and run steps. No tape for this lesson. **Chapters.** `0:00 One file` · `0:40 REST Client` · `2:30 The apic extension` · `5:30 JetBrains and handler blocks` · `7:10 Neovim` · `8:00 The same request, four ways` · `8:50 Checkpoint and exercise`. **Description.** From the [episode template](https://github.com/hungovercoders/apic/blob/main/docs/learn/_episode-template.md). </details> --- # Lesson 13: How apic works inside, and your first contribution URL: https://apic.sh/learn/13-inside-apic/ Lesson 13: follow a request through the packages, the three contracts every change is checked against, and a first contribution end to end. **Goal.** Follow a request through the packages, know the three contracts every change is checked against, and add a small directive end to end with `task check` green. ## You will need - apic installed ([lesson 1](https://apic.sh/learn/01-first-request/)) and `apic demo` running, for the one command below that looks at the tool from outside - Go (the version in `go.mod`) and [Task](https://taskfile.dev) for everything else, and a clone of the repository: ```sh git clone https://github.com/hungovercoders/apic cd apic task build # -> bin/apic task test # no network: every test runs against httptest servers ``` ## Steps ### 1. The lifecycle The [architecture page](https://github.com/hungovercoders/apic/blob/main/docs/architecture.md) has the diagram; this is the walk. A request goes through eight stages, and each is one package: 1. **Parse** (`internal/httpfile`): the file is split on `###`, each block's `# @` comments become directives, then the request line, headers and body are read. Problems become diagnostics with a line, a column and a code; the parser never gives up on a file. 2. **Discover** (`internal/project`): `apic.yaml`, the env files, every `.http` file under the root, indexed by name. `Validate` adds the project-level checks you met in lesson 4. 3. **Resolve** (`internal/runner` with `template`, `env`, `session`): every `{{placeholder}}` looked up in the precedence order from lesson 2; a missing one stops here with exit 2, unless a `# @ref` names the request that captures it. 4. **Apply auth** (`internal/auth`): `# @auth` becomes a header, a SigV4 signature, a cached OAuth2 token or a command's output. 5. **Send** (`net/http`): one attempt per `# @retry` round, with the timeout, the TLS settings and the cookie jar. 6. **Capture and assert** (`internal/selector`, `internal/assert`): the body is read once; selectors pull values out and assertions are evaluated. A failure is exit 1. 7. **Persist** (`internal/session`): captures and cookies to `.apic/`. 8. **Render** (`internal/output`): the same `Result` becomes the terminal report, the `--json` line, the UI panes and the MCP result. You can see stage 8's contract from outside, and it is the one an agent, the UI and the VS Code extension all read. Every key of a `list` entry: <!-- learn --> ```sh apic list -C apic-demo --json | jq -c '.requests[0] | keys' ``` ``` ["asserts","captures","description","file","id","line","method","name","steps","url"] ``` (`refs` appears on `whoami`, which declares one; a key that is empty is left out.) Keep that list in mind: the directive you add in step 4 will put a key on it. ### 2. How the code is tested Three habits run through the tests, and a change that follows them is easy to accept: - **The parser has a golden file.** `internal/httpfile/testdata/sample.http` holds one of everything the parser understands, and `TestParseSample` in `parse_test.go` checks the fields it produces. A new piece of syntax is a case in that file first. - **The runner talks to `httptest`.** `internal/runner/runner_test.go` starts an `httptest.NewServer` per test with handlers that play the API, so a test can hand back a 401, a redirect or a slow body without a network. The same goes for `internal/bdd` and `internal/mcp`. - **The UI is driven headlessly.** `internal/ui/headless.go` has `Press` and `Resize`; tests and the screenshot generator (`task shots`) call them, so a screenshot in the docs is what the UI draws. ```sh go test ./internal/httpfile/ -run TestParseSample -v ``` ``` === RUN TestParseSample --- PASS: TestParseSample (0.00s) PASS ``` ### 3. The three contracts Every review asks the same three questions, and the tree enforces each: | Contract | Enforced by | |---|---| | **The dialect is REST Client's and JetBrains'.** Everything apic adds is a `# @` comment. | The golden file; `TestGrammarMatchesKnownDirectives`, which fails when the VS Code grammar and the parser disagree on the directive list; `validate` warning rather than failing on an unknown directive. | | **`--json` and the exit codes are stable.** Keys are only added; 0, 1, 2 and 3 keep their meanings. | `runner.ExitCode` uses `errors.As`, `errorlint` is on so a wrapped `TransportError` cannot become a 2, and `TestExitCodeUnwraps` pins it. | | **Every command is non-interactive.** `apic ui` is the one exception. | Every CLI test runs with no terminal; the device-code and authorization-code prompts go to stderr and never block on stdin, and the authorization-code grant refuses to start without a terminal. | `task check` is what CI runs: lint (with `errorlint`, `gosec`, `bodyclose` and friends), tests, the race detector, the licence check and the examples. A green `task check` locally is usually a green pull request. ### 4. Add a directive: `# @tag` The [architecture page](https://github.com/hungovercoders/apic/blob/main/docs/architecture.md#how-to-add-things) has the checklist; walk it with a small, real directive. `# @tag smoke` labels a request, repeatable, and `apic list --json` surfaces the tags so an agent or a script can pick the smoke set. Five edits and a test. **Parse it.** The parser already keeps every `# @key value` on the request as a `Directive`; it only needs to know the name, or `validate` warns about it. In `internal/httpfile/parse.go`, one line in `KnownDirectives`: ```go "tag": "label for filtering: `# @tag smoke`, repeatable", ``` and a case in the golden file, `testdata/sample.http`, as a new block at the end of the file: ```http ### Tagged # @name tagged # @tag smoke # @tag users GET {{baseUrl}}/health ``` At the end, not in the middle: `TestParseSample` pins line numbers and request positions throughout the file, the multipart parts among them, so two lines inserted in the middle would fail it. It also counts the requests, so the count goes from 9 to 10, and one assertion that `f.Requests[9]` carries two `tag` directives pins the new case. **Tell the grammar.** `editors/vscode/syntaxes/apic-directives.injection.json` lists the known directives in one alternation; add `tag` to it, or `TestGrammarMatchesKnownDirectives` fails on the next `go test`. That test is the dialect contract at work. **Surface it.** `apic list` builds its entries in `internal/cli/list.go`. Give `listEntry` a field and fill it from the directives: ```go Tags []string `json:"tags,omitempty"` ``` ```go for _, d := range r.Directives { if d.Key == "tag" { e.Tags = append(e.Tags, d.Value) } } ``` `omitempty` keeps the shape identical for every request without tags, which is what "keys are only added" means in practice. **Give it a place in the canonical order.** `directiveRank` in `internal/httpfile/format.go` orders the known directives for `apic fmt`; a tag reads best beside `description`, so slot it there. Without a rank it would still work, sorted after the known ones. **Document it.** A row in the directive table of the site's `format.md`, a line in its `cheatsheet.md`, and `tags` in the `list --json` note of its `cli.md`. **Test it.** `internal/cli/ref_test.go` shows the pattern: write a project to a temp directory, run `list --json`, assert on the text. Add a request with two tags and assert on `"tags": ["smoke", "users"]`. Then: ```sh task check ``` ``` task: [lint] golangci-lint run ./... 0 issues. task: [test] go test ./... ok github.com/hungovercoders/apic/internal/cli ok github.com/hungovercoders/apic/internal/httpfile … ``` The whole change is under fifty lines, and every one of them has a test or a check that would have caught its absence: that is what the checklist is for. ### 5. Open the pull request `CONTRIBUTING.md` is short, and the parts that matter for a first change: - A test next to it, that fails without the fix. Revert the fix once and watch it go red; that is the proof. - Docs in the same change: a new directive needs `format.md` and the cheat sheet, a new command the README table, `cli.md` and the cheat sheet. - A commit message that says why. The diff already says what. - `task check` green before you push. If the UI changed, `task shots`; if a lesson changed, `task learn:check`. Push a branch and open the pull request; CI runs the same `task check` plus the docs build, the course harness and the extension's tests. ## Checkpoint `task check` is green with the new directive and its test, and: ```sh bin/apic list -C apic-demo --json | jq -c '[.requests[] | select(.tags)] | length' ``` prints the number of requests you tagged in the demo project (the bundled project has none until you add some, so tag one and see `1`). ## Exercise Pick a `P3` issue from the [tracker](https://github.com/hungovercoders/apic/issues?q=is%3Aissue+is%3Aopen+label%3AP3) and open a pull request for it. `P3` issues are small and self-contained on purpose. <details> <summary>Solution</summary> There is no single one. A good first pull request has the shape of step 4: a change of a few dozen lines, a test that fails without it, the docs it needs, and a commit message that starts with the reason. Say in the description what you checked and how; reviewers read that first. </details> ## Going further - [Architecture](https://github.com/hungovercoders/apic/blob/main/docs/architecture.md): the diagram, the package map and the checklists for a directive, a Gherkin step, a command and a config key - [AGENTS.md](https://github.com/hungovercoders/apic/blob/main/AGENTS.md): the conventions, including the ones that are easy to trip over - [CONTRIBUTING.md](https://github.com/hungovercoders/apic/blob/main/CONTRIBUTING.md) and [SECURITY.md](https://github.com/hungovercoders/apic/blob/main/SECURITY.md) <details> <summary>Episode script</summary> **Length.** 12 minutes; a code walkthrough in an editor. **Cold open (0:00).** The lifecycle diagram, then `apic run whoami` with `login` running first. "Eight stages, eight packages. Here is where each of those lines came from." **Talking points.** 1. The lifecycle, one package per stage, with the file open for each. 2. The golden file, an `httptest` handler in a runner test, `Press` in a UI test. 3. The three contracts and the test behind each; `task check`. 4. `# @tag` end to end: `KnownDirectives`, the golden case, the grammar test going red then green, `listEntry`, `directiveRank`, the docs rows, the CLI test. 5. `task check` green; the pull request and what CONTRIBUTING asks. 6. Checkpoint, then the `P3` exercise. **Shot list.** An editor with the repository open, the terminal in a split; the diagram from the architecture page full-screen for the open. No tape for this lesson. **Chapters.** `0:00 Eight stages` · `2:00 How it is tested` · `4:00 The three contracts` · `5:30 Add # @tag` · `10:00 The pull request` · `11:00 Checkpoint and exercise`. **Description.** From the [episode template](https://github.com/hungovercoders/apic/blob/main/docs/learn/_episode-template.md). </details> --- # The .http format apic understands URL: https://apic.sh/format/ The .http request format apic runs: structure, # @directives, variables and their precedence, selectors, assertion operators, flows, dependencies, retries and cookies. apic runs the common subset of the `.http` request format shared by VS Code REST Client, JetBrains HTTP Client, kulala.nvim and httpyac. Everything apic adds is a `# @directive` comment placed **before the request line**, which those tools treat as a comment, so one file works everywhere. ```http @baseUrl = https://api.example.com ### 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": "{{user}}", "password": "{{password}}"} ### Fetch a user # @name get-user # @description Fetch a single user by id # @assert status == 200 # @assert body.$.id == {{userId}} GET {{baseUrl}}/users/{{userId}} ?expand=profile Authorization: Bearer {{token}} Accept: application/json ``` ## Structure | Element | Syntax | |---|---| | Request separator | `###` optionally followed by a title, used as the description | | File variable | `@name = value` anywhere outside a body; last declaration wins; values may use `{{vars}}` | | Comment | `# text` or `// text` | | GraphQL request | `GRAPHQL {{baseUrl}}/graphql` (or a `X-REQUEST-TYPE: GraphQL` header): the body is the query, a JSON object after a blank line is the variables; see [GraphQL](#graphql) | | Directive | `# @key value` before the request line | | Request line | `METHOD url [version]`, the version `HTTP/1.1` or `HTTP/2`; a bare URL means `GET`. See [HTTP version](#http-version) | | Query continuation | indented lines starting with `?` or `&` are appended to the URL | | Headers | `Name: value` lines until the first blank line. Any RFC 7230 token character may appear in a name, except that a line starting with `#` is a comment | | Body | everything after the blank line until the next `###` | | Body from file | `< ./payload.json` (raw) or `<@ ./payload.json` (with `{{vars}}` substituted), relative to the `.http` file | | Multipart body | `Content-Type: multipart/form-data; boundary=X` with the parts written between `--X` lines; a part whose content is `< ./file` sends that file's bytes. See [Multipart uploads](#multipart-uploads) | | Save the response | `>> ./out.json` after the body writes the response body there (fails if the file exists); `>>! ./out.json` overwrites. Relative to the `.http` file, inside the project. See [Saving a response](#saving-a-response) | | Editor script blocks | `> {% … %}`, `< {% … %}` and `> ./handler.js` are skipped with a warning, not sent — apic has no scripting. `apic validate` lists them | Files are found by walking the project root for `*.http` and `*.rest`, skipping hidden directories, `node_modules`, `vendor` and `testdata`. ## Directives | Directive | Meaning | |---|---| | `# @name get-user` | Name used on the command line and by MCP. Unnamed requests are addressed as `file.http#3`. | | `# @description text` | One line shown by `list` and `describe`; defaults to the `###` title. | | `# @capture name = selector` | After the response arrives, store the selected value as `name`. It is available to later requests in the same run and persisted in `.apic/session.json` for later invocations. | | `# @assert selector op value` | Check the response. Failures set `ok: false` and exit code 1. | | `# @auth type ...` | Attach credentials: `none`, `bearer`, `basic`, `apikey`, `digest`, `aws`, `oauth2` or `exec`. See [auth.md](https://apic.sh/auth/). | | `# @step a user named {name} exists` | A Gherkin phrase that runs this request from a `.feature` file; `{name}` becomes a variable. Repeatable. See [testing.md](https://apic.sh/testing/). | | `# @ref login` | Run `login` first when this request is missing a variable (once per invocation). Repeatable. See [Dependencies](#dependencies). | | `# @forceRef login` | Run `login` first every time this request runs. Repeatable. | | `# @no-redirect` | Do not follow 3xx redirects. | | `# @no-session` | Do not persist this request's captures. | | `# @no-cookies` | Send no cookies with this request and keep none it sets, when the [cookie jar](#cookies) is on. | | `# @timeout 10s` | Per-request timeout. | | `# @retry 10 2s` | Re-send until every assertion passes, up to 10 times, 2s apart (default 1s). See [Retries](#retries). | | `# @sleep 2s` | Wait this long before sending, after any `# @ref` ran. See [Pauses and disabled requests](#pauses-and-disabled-requests). | | `# @disabled` | Keep the request out of flows: running its file skips it. Asking for it by name still sends it. | | `# @note text` | Free text. Accepted and ignored, for REST Client compatibility. | | `# @prompt name` | Accepted and ignored: apic never prompts. Pass the value with `--var name=...`, or put it in an env file. | Unknown directives are reported as warnings by `apic validate` and ignored. ## Variables `{{name}}` placeholders are resolved from these sources, first match wins: 1. `--var name=value` on the command line (or `vars` in an MCP call) 2. `APIC_VAR_name` in the shell environment 3. values captured earlier in this run 4. the session (`.apic/session.json`), per environment 5. `http-client.private.env.json` for the selected environment 6. `http-client.env.json` for the selected environment (`$shared` applies to all) 7. `.env` in the project root 8. `@name = value` in the `.http` file `describe` shows which source each variable resolved from. ### Environment files ```json { "$shared": { "userId": 42 }, "dev": { "baseUrl": "https://dev.example.com" }, "prod": { "baseUrl": "https://api.example.com" } } ``` Select with `--env dev`, or set a default in `apic.yaml` (`env: dev`). Keep secrets in `http-client.private.env.json` and gitignore it; apic masks values from that file, from `.env`, from the session, from `--var` and `APIC_VAR_`, and values captured this run, in `describe`, `env` and MCP output. A JetBrains `SSLConfiguration` entry in either file is not a variable: it configures a client certificate, see [auth.md](https://apic.sh/auth/#tls-and-client-certificates). Neither is a `Security` block, whose `Auth` configurations requests use as `{{$auth.token("name")}}`; see [JetBrains projects](https://apic.sh/auth/#jetbrains-projects). ### Built-ins | Placeholder | Value | |---|---| | `{{$uuid}}` / `{{$guid}}` | random UUID v4 | | `{{$timestamp}}` / `{{$timestamp -1 d}}` | Unix seconds, with an optional offset | | `{{$isoTimestamp}}` | RFC 3339 UTC | | `{{$datetime rfc1123}}` / `{{$datetime iso8601}}` / `{{$datetime "2006-01-02"}}` / `{{$datetime iso8601 1 h}}` | formatted UTC time (Go layout for custom formats), with an optional offset | | `{{$localDatetime}}` / `{{$localDatetime rfc1123 -1 d}}` | the same in the machine's own zone; the format is optional | | `{{$randomInt 1 100}}` | random integer in [min, max) | | `{{$random.integer(1, 100)}}` / `{{$random.float(0, 1)}}` | JetBrains' random numbers: an integer in [min, max), a float with three decimals; `(0, 1000)` without arguments | | `{{$random.alphabetic(10)}}` / `{{$random.alphanumeric(10)}}` / `{{$random.hexadecimal(10)}}` | random text of that length (10 without arguments) | | `{{$random.email}}` / `{{$random.uuid}}` | `<8 letters>@example.com`, a UUID v4 | | `{{$processEnv NAME}}` / `{{$env.NAME}}` | shell environment variable | | `{{$dotenv NAME}}` | value from `.env` | | `{{$projectRoot}}` | the project root, absolute, for `< {{$projectRoot}}/fixtures/x.json` | | `{{$auth.token("name")}}`, `{{$auth.idToken("name")}}` | the access or ID token of a JetBrains `Security.Auth` configuration in the env files; see [JetBrains projects](https://apic.sh/auth/#jetbrains-projects) | An offset is `<n> <unit>`, as REST Client writes it: `-1 d`, `2 h`, `30 m`, `-10 s`, `500 ms`, `1 w`, `1 M` (months), `1 Q` (quarters), `1 y`. Months, quarters and years move by the calendar, so the 31st plus a month rolls forward the way Go's `AddDate` does. The random values are sample data for payloads, not credentials; `$exampleServer` is a JetBrains concept apic does not add. ### Response references Within a single run of several requests (a flow), a later request may read an earlier named response directly, using REST Client syntax: ``` Authorization: Bearer {{login.response.body.$.access_token}} X-Request-Id: {{login.response.headers.x-request-id}} ``` `@capture` is the same idea with a short name that also persists between runs. A reference to a request that has not run is a missing variable; a [`# @ref`](#dependencies) to that request runs it first. ## Saving a response A `>>` line after the body, as REST Client and JetBrains write it, saves the response body to a file: ``` ### Export # @name export-csv GET {{baseUrl}}/reports/daily.csv >>! ./fixtures/daily.csv ``` `>> path` creates the file and fails (the request is not OK) when it already exists; `>>! path` overwrites. The path is relative to the `.http` file and must stay inside the project (`apic validate` reports `bad-save-path` otherwise); directories are created. The bytes are written as they came, so a binary download stays intact, and the file is created `0600` when a secret went into the request (a private variable, a capture, a credential), `0644` otherwise. The run's output says `↳ saved to fixtures/daily.csv`, `--json` carries `saved_to`, and a body that is not text is summarised (`binary body · 12 KB · image/png`) rather than printed. `apic run --output <file>` does the same for one request without editing the file. ## GraphQL Both editors have a GraphQL shape, and apic runs both. JetBrains writes the method as `GRAPHQL`; REST Client marks a `POST` with an `X-REQUEST-TYPE: GraphQL` header. Either way the body is the query, and a JSON object after a blank line is the variables: ``` ### Todos by state # @name todos-by-state # @assert body.$.data.todos.# >= 1 GRAPHQL {{baseUrl}}/graphql Authorization: Bearer {{token}} query Todos($done: Boolean) { todos(done: $done) { id title } } {"done": {{done}}} ``` apic sends it as a `POST` with `Content-Type: application/json` (unless the request sets its own) and the body `{"query": "...", "variables": {...}}`, which is what a GraphQL server reads. Placeholders resolve in both halves, the `X-REQUEST-TYPE` header never goes on the wire, and the variables are optional. `apic list` shows the method as written; `describe`, `curl` and `--json` show the POST and the JSON body actually sent. Selectors are the plain ones: `body.$.data.todos.#`. A query can come from a file too (`<@ ./todos.graphql`); a request without a query, or whose variables are not a JSON object, is a `bad-graphql` error in `apic validate`. ## Selectors Used by `@capture` and `@assert`: | Selector | Value | |---|---| | `status` | status code, e.g. `200` | | `statusText` | e.g. `OK` | | `header.<name>` | first value of a response header, case-insensitive | | `header.<name>.#` / `header.<name>[1]` | how many values a header has, and the n-th (from 0; `[-1]` is the last), for `Set-Cookie`, `Link` and the like | | `cookie.<name>` | value of a cookie the response set (`Set-Cookie`), whether or not the jar is on | | `body` | raw body | | `body.$` | whole body (must be JSON) | | `body.$.<path>` | a JSONPath into the body; see [Body paths](#body-paths) | | `duration` | round-trip time in milliseconds | ### Body paths The path after `body.$` is JSONPath, as Hurl, Postman and Bruno write it: | Path | Selects | |---|---| | `body.$.items[0].id`, `body.$["key with dots"]` | a key or an index; a bare key runs to the next `.` or `[` | | `body.$.items[-1]` | an index counted from the end | | `body.$.items[1:3]`, `[:2]`, `[-2:]` | a slice, end exclusive | | `body.$.items[*].id`, `body.$.meta.*` | every element or value | | `body.$..id` | every `id` at any depth (recursive descent) | | `body.$.items[?(@.done == true)].id` | the elements a filter keeps: `==`, `!=`, `<`, `<=`, `>`, `>=` against a number, a quoted string, `true`, `false` or `null`; `=~ /^a/` (add `i` after the closing slash to ignore case); `@.owner` alone for presence and `!@.owner` for absence; `&&` and `||` between terms; the `@` path can hold brackets of its own, as in `@.tags[0] == "red"` | | `body.$.items.#`, `body.$.items.length` | at the end, how many: an array's elements, an object's keys, a string's characters, or the matches of a wildcard, slice, filter or `..`; a number, boolean or null has no count | A path through a wildcard, slice, filter or `..` selects every match, and its value is a JSON array of them (`["a","c"]`); no matches means nothing is there, so `exists` fails and `.length` is `0`. A single value is the text itself for a string and JSON for anything else, exactly as the server sent it. An object with a real `length` key keeps it: `body.$.length` reads that key, and inside a filter `@.length` on an object is only ever that key, so `[?(@.length)]` asks whether it is there. A filter's `!=` also keeps the elements that lack the key, as RFC 9535 says: `[?(@.status != "done")]` keeps an element with no `status`. Every other comparison needs the value to be there. Paths written for gjson, which apic used before filters existed, still select what they did: a numeric key on an array is an index (`body.$.items.0.id`), and `#` in the middle of a path maps over an array (`body.$.items.#.id`), so a count after it is each element's own (`body.$.items.#.tags.#` is `[2,0]`). gjson's `#(...)` queries are not supported; write them as filters, `body.$.items[?(@.id == 2)].name`. Parentheses inside a filter, unions (`[0,1]`) and slice steps (`[0:9:2]`) are not supported either; `apic validate` names the part it cannot read. ## Assertion operators `==`, `!=`, `<`, `<=`, `>`, `>=` (numeric when both sides parse as numbers), `contains`, `startsWith`, `endsWith`, `matches` (Go regular expression), `exists`, `not exists`. The right-hand side may contain `{{placeholders}}` and may be quoted. ``` # @assert status < 300 # @assert body.$.items.# >= 1 # @assert header.content-type contains json # @assert body.$.email matches ^[^@]+@example\.com$ # @assert body.$.error not exists # @assert body.$.items[?(@.done == true)].length == 2 # @assert header.set-cookie.# >= 1 ``` ### The shape of a response These say what a value is rather than what it equals: | Assertion | Passes when | |---|---| | `body.$.id isInteger` | the value is a whole number; also `isNumber`, `isString`, `isBoolean`, `isArray`, `isObject`, `isNull` | | `body.$.id not isString` | the `not` form of any of them | | `body.$.items isEmpty` / `not isEmpty` | an empty (or non-empty) string, array or object | | `body.$.items length == 3` | its length compares: a string's characters, an array's elements, an object's keys; any of `==`, `!=`, `<`, `<=`, `>`, `>=` | | `body.$ matchesSchema ./schemas/user.json` | it validates against a JSON Schema | Types are JSON types: a status, a duration and a count are numbers; headers, cookies, `statusText` and the raw `body` are strings. A failed type check reports what the value is (`actual: number`). `matchesSchema` reads a JSON Schema file (draft 2020-12 or draft-07, `$ref` within the file) relative to the `.http` file and inside the project; a failure reports the path in the document and the rule it broke. `apic validate` reports a schema file that does not exist as `missing-schema-file`. ``` ### Get a user, checked for shape # @name get-user # @assert status == 200 # @assert body.$ matchesSchema ./schemas/user.json # @assert body.$.id isInteger # @assert body.$.roles not isEmpty GET {{baseUrl}}/users/{{userId}} ``` ## Flows `apic run file.http` runs every request in the file in order and stops at the first failed assertion, failed capture or transport error (use `--keep-going` to continue). Exit code is 1 if an assertion or capture failed, 2 for a definition problem such as a missing variable, and 3 for a network error. `--json` prints one JSON object per request (NDJSON). ## HTTP version With no version on the request line, apic does what browsers do: HTTP/2 when the server offers it over TLS, HTTP/1.1 otherwise. A version pins it: ```http ### A gateway whose HTTP/2 is broken GET https://legacy.example.com/report HTTP/1.1 ### Prove the API speaks HTTP/2 GET https://api.example.com/health HTTP/2 ``` - `HTTP/1.1` (or `HTTP/1.0`, sent as 1.1) never uses HTTP/2, even when the server offers it. - `HTTP/2` requires it: over `https://` the request fails with exit code 3 when the server does not offer HTTP/2, and over plain `http://` it is a usage error, because apic does not send cleartext HTTP/2 (h2c). - `HTTP/3`, or anything else, is reported by `apic validate` as `bad-http-version` and refused. `run -v` puts the protocol the response came over in front of the status (`HTTP/2.0 200 OK`), `--json` has it as `response.proto` and the pinned version as `request.http_version`, and `apic curl` adds `--http1.1` or `--http2`. `apic import --curl` reads those two flags back onto the request line. ## Dependencies A request that needs a value another request captures can say so, and apic runs that request first when the value is missing: ```http ### Log in and keep the token # @name login # @capture token = body.$.access_token POST {{baseUrl}}/auth/login ### Who am I # @name whoami # @ref login GET {{baseUrl}}/me Authorization: Bearer {{token}} ``` `apic run whoami` on a fresh session runs `login`, then `whoami`; with the token already in the session it runs only `whoami`. A `# @ref` runs at most once per invocation, so a flow that needs `login` twice logs in once, and the target's own `# @ref` lines apply too. `# @forceRef login` runs `login` first every time, for a token that must be fresh. The target is any run target (`login`, `auth.http#login`) that names exactly one request; a target that does not, or a chain that leads back to itself, is an error `apic validate` reports as `bad-ref` or `ref-cycle`. A [response reference](#response-references) counts as a missing value too, which is how httpyac files use `# @ref`: with `# @ref login`, `{{login.response.body.$.access_token}}` runs `login` first and reads its response. A dependency that fails (an assertion, a capture, the network) stops the request that depends on it: the run reports the dependency's result, then the request as failed without sending it. The output shows what ran first (`↳ ran login first (# @ref)` in the terminal; under `--json` the dependency prints as its own object before the request, and MCP `run_request` nests it under `ran_first`; see [cli.md](https://apic.sh/cli/#apic-run)). ## Retries A request whose assertions describe a state the API will reach, not the one it is in, can wait for it: ```http ### Poll until the job is done # @name wait-for-job # @retry 10 2s # @assert status == 200 # @assert body.$.state == done GET {{baseUrl}}/jobs/{{jobId}} ``` `# @retry <attempts> [interval]` sends the request again until every assertion passes or the attempts are spent, waiting `interval` between attempts (a Go duration such as `500ms` or `2s`; default `1s`). A transport error counts as a failed attempt too. Each failed attempt prints a line as it happens (`attempt 1/10 · body.$.state == done: got "running"`), the report of the attempt that counted says how many it took, and `--json` carries `attempts`. Captures and the session are written from that final attempt only, and every attempt gets the full `# @timeout`. `retry:` in `apic.yaml` sets a default for requests without their own `# @retry`, `--retry "<attempts> [interval]"` overrides that for one run, and `--no-retry` sends everything once. The order is directive, flag, file. `apic validate` reports a policy it cannot read as `bad-retry`. ## Pauses and disabled requests ```http ### Nightly export, slow and rate limited # @name export # @disabled # @sleep 2s POST {{baseUrl}}/exports ``` `# @sleep <duration>` waits that long (a Go duration such as `500ms` or `2s`) before the request is sent: after any `# @ref` ran and before the first attempt, once however many attempts a `# @retry` makes. Cancelling the run (Ctrl-C, `esc` in the UI) cancels the wait. `describe` shows it, and `apic validate` reports a value it cannot read as `bad-sleep`. `# @disabled` keeps a request in the file without it running in the flow. Running the file skips it: `apic run export.http`, `f` and `a` in the UI, `When I run the file` in a feature and MCP's `run_file`. The flow's output says `skipped (disabled)` and its summary counts it (`2 passed, 1 skipped`); under `--json` the request still prints its object, with `"skipped": "disabled"`, `ok: true` and no `response`. Asking for the request itself sends it as usual: `apic run export`, `apic run export.http#export`, `enter` in the UI, `When I run "export"`, MCP's `run_request`, and a `# @ref` to it. `list` marks it (`"disabled": true`, dimmed in the UI). ## Cookies apic sends no cookies unless a jar is switched on, with `cookies: true` in `apic.yaml` or `--cookies` on the command line. With it on, a cookie a response sets is sent with later requests to the same site, in the same run and in later ones: the jar is stored per environment in `.apic/cookies.json`, beside the session, so a login that answers with a session cookie works like one that answers with a token. ```http ### Log in with a form # @name login # @assert status == 204 # @assert cookie.sid exists POST {{baseUrl}}/login Content-Type: application/x-www-form-urlencoded user={{user}}&password={{password}} ### The cookie goes out by itself # @name me # @assert status == 200 GET {{baseUrl}}/me ``` Which cookies go where follows Go's `net/http/cookiejar`: domain, path, `Secure` and expiry are honoured; there is no public-suffix list, so a cookie set for `example.com` is sent to every host under it. A cookie without an expiry is kept until `apic session clear`, like a captured value. `# @no-cookies` exempts one request, `--no-session` keeps the jar in memory for one command, and `apic test` gives every scenario its own empty jar unless `--use-session` shares the stored one. `Cookie` and `Set-Cookie` headers are masked in output whether or not `--redact` is set. ## Multipart uploads A `multipart/form-data` body is written the way REST Client and JetBrains write it, with the boundary declared in the header and each part between delimiter lines: ```http ### Upload a report # @name upload-report # @assert status == 201 POST {{baseUrl}}/upload Content-Type: multipart/form-data; boundary=WebAppBoundary --WebAppBoundary Content-Disposition: form-data; name="title" Quarterly report for {{user}} --WebAppBoundary Content-Disposition: form-data; name="file"; filename="report.pdf" Content-Type: application/pdf < ./report.pdf --WebAppBoundary-- ``` apic reads the parts and assembles the body itself, so a part whose only content is `< ./report.pdf` sends the file's bytes (binary-safe, with `Content-Length` set), not the reference as text. `<@ ./file` substitutes `{{variables}}` inside the file first, and text parts and part headers are templates like the rest of the request. Paths are relative to the `.http` file and confined to the project root, like a whole-body `< file`. `apic validate` reports a body under a `multipart/form-data` content type that has no boundary, or whose parts are not laid out between the delimiters (`bad-multipart`), and a part file that does not exist (`missing-body-file`). In output the body is shown as `<multipart: 2 parts, 1 file>` rather than its bytes; `apic curl` turns the parts into `--form-string` and `-F name=@file` options. ## Canonical form `apic fmt` rewrites a file the way this page writes them: one blank line between blocks, directives in a fixed order (`name`, `description`, `disabled`, `step`, `auth`, `ref`, `forceRef`, `sleep`, `retry`, `timeout`, `no-redirect`, `no-session`, `no-cookies`, `assert`, `capture`, then the rest as written), header names in canonical case, query continuations indented, JSON bodies pretty-printed when they hold no placeholders. Every other body is kept byte for byte; comments stay with the directive below them, and unknown directives, file bodies and editor script blocks are kept as they are. Formatting twice changes nothing. See [cli.md](https://apic.sh/cli/#apic-fmt). ## Project layout ``` api/ apic.yaml optional: env, dir, timeout, retry, cookies, history, proxy, noProxy, maxBodyBytes, tls, auth.default, auth.allowExec, test.paths features/*.feature Gherkin specs run by `apic test` http-client.env.json public per-environment variables http-client.private.env.json secrets (gitignored) .env optional KEY=value auth.http users.http .apic/session.json captured values (created by apic, self-ignored) ``` --- # Authentication URL: https://apic.sh/auth/ Attach credentials with # @auth or auth.default: bearer, basic, API key, digest, OAuth2 with caching and refresh, AWS SigV4, any CLI that prints a token, and TLS client certificates. apic can attach credentials to a request with a `# @auth` directive, or to every request in a project with `auth.default` in `apic.yaml`. Like every apic directive it is a comment, so the files still work in VS Code, JetBrains and Neovim. ```http ### List orders (signed with AWS SigV4) # @name list-orders # @auth aws service=execute-api region=eu-west-2 GET {{baseUrl}}/orders ``` | Type | Spec | What it does | |---|---|---| | `none` | `# @auth none` | Send no credentials. Overrides a project default. | | `bearer` | `# @auth bearer {{token}}` | `Authorization: Bearer <token>` | | `basic` | `# @auth basic {{user}} {{password}}` | HTTP basic auth (base64 done for you) | | `apikey` | `# @auth apikey {{key}} [header=..] [query=..] [prefix=..]` | The key as a header (default `X-Api-Key`, no prefix) or a query parameter | | `digest` | `# @auth digest {{user}} {{password}}` | HTTP digest auth (RFC 7616), answering the server's challenge | | `aws` | `# @auth aws [service=execute-api] [region=..] [profile=..]` | AWS Signature V4 using the standard credential chain | | `oauth2` | `# @auth oauth2 tokenUrl=.. clientId=.. ...` | Client credentials, password, device code or authorization code (PKCE) grant; token cached and refreshed | | `exec` | `# @auth exec <command> [args]` | Run a command and use its output as the token | Values in a spec may contain `{{placeholders}}`; they resolve like any other variable, so secrets belong in `http-client.private.env.json`, `.env` or `APIC_VAR_*` shell variables. Quote values with spaces: `scope="read write"`. ## Project default ```yaml # apic.yaml auth: default: aws region=eu-west-2 service=execute-api allowExec: false ``` Every request without its own `# @auth` uses the default. A request opts out with `# @auth none` or picks something else with its own directive. Because the default may contain `{{variables}}`, one project can point at different identity providers per environment: ```yaml auth: default: oauth2 tokenUrl={{tokenUrl}} clientId={{clientId}} clientSecret={{clientSecret}} ``` with `tokenUrl` and `clientId` in `http-client.env.json` per environment and `clientSecret` in the private file. `apic describe <id>` shows which spec applies and whether its variables resolve. ## bearer and basic ```http # @auth bearer {{token}} # @auth basic {{user}} {{password}} ``` `bearer` is the same as writing the `Authorization` header yourself; it exists so it can be a project default. `basic` base64-encodes `user:password`, which is the part you cannot do in a plain header. See `examples/github/repo.http` for `bearer` against the real GitHub API. ## apikey ```http # @auth apikey {{key}} # @auth apikey {{key}} header=X-Auth-Token # @auth apikey {{key}} query=api_key # @auth apikey {{key}} header=Authorization prefix="Token " ``` The most common credential on the internet, as a type rather than a header you write by hand, so it can be the project default: ```yaml auth: default: apikey {{apiKey}} ``` `header=` names the header (default `X-Api-Key`) and `prefix=` puts text before the key; `query=` sends it as a query parameter instead, which some APIs insist on. Wherever apic shows the request the key is not there: the header is set on the wire only, and in the query form the URL apic prints is the one from the file. A key that contains `=` is still one argument. ## digest ```http # @auth digest {{user}} {{password}} ``` HTTP Digest authentication (RFC 7616). The server answers the first request with a `401` and a challenge; apic computes the response from the credentials, the server's nonce and the request, and sends the request again with the `Authorization` header, so the password never travels. `MD5`, `MD5-sess`, `SHA-256` and `SHA-256-sess` are implemented, with `qop=auth` and `auth-int` (chosen for requests with a body when the server offers it), `opaque`, `userhash` and stale-nonce retry. The challenge is remembered for the rest of the invocation, so later requests to the same server go out authenticated on the first try with the nonce count going up. `run -v` says which happened (`auth: digest: 401 challenge answered (2 requests)`), and `--json` reports `"auth": "digest"`. ## aws ```http # @auth aws # @auth aws service=s3 region=us-east-1 # @auth aws profile=prod ``` Requests are signed with AWS Signature Version 4 (header authentication). apic does not embed the AWS SDK; it implements the signature itself, checked against the official AWS test vectors, and finds credentials the same way the AWS CLI does: 1. `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY` and optional `AWS_SESSION_TOKEN` in the environment (skipped when `profile=` is given explicitly) 2. static keys for the profile in `~/.aws/credentials` or `~/.aws/config` (`AWS_SHARED_CREDENTIALS_FILE` and `AWS_CONFIG_FILE` are honoured) 3. `aws configure export-credentials --profile <name>` when the AWS CLI v2 is installed, which resolves SSO sessions, assumed roles, `credential_process` and everything else the CLI supports The profile is `profile=`, else `AWS_PROFILE`, else `default`. The region is `region=`, else `AWS_REGION`, else `AWS_DEFAULT_REGION`, else the profile's `region`; with none of those the request fails with a clear message. `service=` defaults to `execute-api` (API Gateway); use `s3`, `lambda`, `es`, `aoss`, `appsync` and so on for other services. So on a developer machine with `aws sso login` done, or in CI with keys in the environment, `# @auth aws` works with no apic-specific setup. What is not covered without the CLI is instance-metadata and ECS task credentials; install the CLI there or export keys into the environment. The signature covers the method, path, query, the body hash and the headers present when the request is signed, and the body is sent with `X-Amz-Content-Sha256`. Signing happens after every `{{variable}}` is substituted, so a signed request can still use captured values. If the CLI reports an expired SSO session, its message (for example "run aws sso login") is passed through. ## oauth2 ```http # @auth oauth2 tokenUrl={{tokenUrl}} clientId={{clientId}} clientSecret={{clientSecret}} scope="api.read api.write" ``` | Option | Meaning | |---|---| | `tokenUrl=` | Token endpoint. Required. | | `clientId=` | Client id. Required. | | `clientSecret=` | Client secret, if the client is confidential. | | `grant=` | `client_credentials` (default), `password`, `device_code` or `authorization_code`. | | `scope=` | Space-separated scopes; quote them. | | `audience=` | Sent as `audience` (Auth0, some others). | | `username=`, `password=` | For `grant=password`. | | `deviceUrl=` | Device authorization endpoint, for `grant=device_code`. | | `authUrl=` | Authorization endpoint, for `grant=authorization_code`. | | `redirectPort=` | Loopback port for the redirect, for `grant=authorization_code`. Default: a free one. | | `redirectUrl=` | The whole redirect URI instead, as the provider has it registered: `http://localhost:<port>/<path>`. apic listens on that port and path and sends the URI as written. | | `clientAuth=` | `body` (default: `client_id`/`client_secret` in the form) or `basic` (HTTP basic auth on the token request). | The access token is cached in the session (`.apic/session.json`) for the current environment, keyed by every option that changes the token: the token and device URLs, the client id, secret and auth method, the grant, scope, username, password, audience and, for the authorization code grant, the authorization URL. It is reused until a minute before it expires, then refreshed with the refresh token when the server issued one, otherwise re-requested. `apic session` shows the cached entries and their remaining lifetime; `apic session clear` forgets them. `--no-session` fetches a fresh token on every run. See `examples/spotify/search.http` for `client_credentials` with `clientAuth=basic` against the real Spotify Web API. This covers Entra ID (Azure AD), Okta, Auth0, Keycloak, Cognito and most other providers for machine-to-machine access, since they all speak the client credentials grant. ### Device code ```http # @auth oauth2 grant=device_code tokenUrl={{tokenUrl}} deviceUrl={{deviceUrl}} clientId={{clientId}} scope=openid ``` For a human at a terminal signing in as themselves. apic prints a URL and a code on stderr, waits while you approve in a browser, then continues. The token is cached like any other, so you sign in once per expiry. Do not use this from an unattended agent; it will wait until the code expires. ### Authorization code with PKCE ```http # @auth oauth2 grant=authorization_code authUrl={{authUrl}} tokenUrl={{tokenUrl}} clientId={{clientId}} scope="openid profile" redirectPort=8976 ``` The flow behind "sign in as yourself" for most user-facing APIs (Google, GitHub Apps, Entra ID delegated scopes), for providers that do not offer device code. apic listens on a loopback port, opens the provider's sign-in page in your browser (and prints the URL on stderr in case it cannot), receives the code on the redirect, and exchanges it for a token: ``` To sign in, open https://login.example.com/authorize?client_id=... (the redirect URI is http://127.0.0.1:8976/callback; register it with the provider if it asks) Waiting for the browser... ``` PKCE (`S256`) is always on, so a public client needs no `clientSecret=`; give one for a confidential client. `redirectPort=` fixes the port when the provider wants the exact redirect URI registered (`http://127.0.0.1:<port>/callback`); without it apic picks a free one. The `state` of the redirect is checked, and the wait gives up after five minutes. The token is cached and refreshed exactly like the other grants, so the browser is needed once per refresh-token lifetime. And it is a human flow: under `--json`, from the MCP server, from `apic test`, or when stdin or stderr is not a terminal, apic never starts a browser. With no cached token the request then fails with exit 2 and a message saying to run it once interactively; after that the cached token serves every unattended run until the refresh token expires. ### JetBrains projects A project set up for JetBrains HTTP Client keeps its OAuth2 settings in the env files, under `Security.Auth`, and asks for a token in the request: ```json // http-client.env.json { "dev": { "Security": { "Auth": { "my-api": { "Type": "OAuth2", "Grant Type": "Client Credentials", "Token URL": "https://login.example.com/oauth2/token", "Client ID": "{{clientId}}", "Scope": "api.read", "Custom Request Parameters": {"audience": "api://my-api"} } } } } } // http-client.private.env.json {"dev": {"Security": {"Auth": {"my-api": {"Client Secret": "…"}}}}} ``` ```http GET {{baseUrl}}/orders Authorization: Bearer {{$auth.token("my-api")}} ``` apic runs those files as they are. `{{$auth.token("name")}}` runs the configuration's grant through the same code and the same session cache as `# @auth oauth2`, so a token is fetched once and refreshed as above, and `{{$auth.idToken("name")}}` gives the ID token (ask for the `openid` scope). The private file's fields are merged over the public file's, an environment's over `$shared`'s, so the secret can live where it belongs. The value is a secret: it is masked wherever the request is shown. | JetBrains field | Maps to | |---|---| | `Type` | `OAuth2`; anything else is refused. | | `Grant Type` | `Client Credentials`, `Password`, `Device Authorization` or `Authorization Code`. `Implicit` is refused (OAuth 2.1 drops it); use Authorization Code, which apic always runs with PKCE. | | `Token URL`, `Auth URL`, `Device Auth URL` | `tokenUrl=`, `authUrl=`, `deviceUrl=` | | `Client ID`, `Client Secret`, `Scope` | `clientId=`, `clientSecret=`, `scope=` | | `Username`, `Password` | `username=`, `password=` for the Password grant | | `Redirect URL` | `redirectUrl=`: apic listens there for the browser's redirect | | `Client Credentials` | `basic` is `clientAuth=basic`; `in body` (the default) and `none` send the client id in the form | | `Custom Request Parameters` | `audience` is sent; other parameters are reported by `apic validate` and not sent | | `Use ID Token` | `$auth.token` gives the ID token | | `PKCE`, `Acquire Automatically` | Accepted: apic always uses PKCE and fetches a token when a request needs one | String fields may use `{{placeholders}}`. `apic env` lists the configurations of the current environment with the spec each maps to (secrets masked); `apic describe` names the configuration a placeholder uses without fetching a token; `apic validate` reports a configuration apic cannot use as `bad-auth-config` and each field it ignores as `unknown-auth-key`. ## exec ```http # @auth exec gcloud auth print-access-token # @auth exec az account get-access-token --query=accessToken --output=tsv ttl=30m # @auth exec op read op://vault/api/token header=X-Api-Key prefix= ``` Runs the command (directly, not through a shell) and uses its trimmed stdout as the credential. Options after the command: | Option | Meaning | |---|---| | `header=` | Header to set. Default `Authorization`. | | `prefix=` | Text before the value. Default `Bearer`; `prefix=` (empty) sends the raw value. | | `ttl=` | Cache the output in the session for this long, e.g. `ttl=30m`. Off by default. | Because this executes commands found in a text file, and agents edit text files, it is disabled unless the project opts in: ```yaml # apic.yaml auth: allowExec: true ``` Without it, `apic validate` warns and `apic run` refuses. Use `exec` for Google Cloud, Azure CLI sessions, password managers, Vault, or any provider apic does not know about. ## TLS and client certificates An API behind a private CA, or an mTLS gateway that asks for a client certificate, is configured in `apic.yaml`; paths are relative to the project root and confined to it: ```yaml tls: caFile: certs/internal-ca.pem # trusted in addition to the system roots certFile: certs/client.pem # presented when the server asks keyFile: certs/client-key.pem # defaults to certFile when both are in one file verifyHost: true # the default; --insecure turns it off for one command hosts: # per-host overrides, by name or *.suffix api.internal.example.com: {certFile: certs/internal.pem, keyFile: certs/internal-key.pem} "*.dev.example.com": {verifyHost: false} ``` For one command, `--cacert`, `--cert` and `--key` override all of that, and `--insecure` still means what it means. A JetBrains project needs no change: the `SSLConfiguration` block in `http-client.env.json` or the private file is read for the selected environment (`clientCertificate` with `path` and `keyPath`, and `verifyHostCertificate`); a key marked `hasCertificatePassphrase` is refused, since apic never prompts. The precedence is the flags, then a matching `tls.hosts` entry, then the environment's `SSLConfiguration`, then `tls`. Keys are PEM. A key file anyone on the machine can read is refused with its mode, the way ssh refuses one: `chmod 600` it. PKCS#12 bundles are not read; convert with `openssl pkcs12 -in client.p12 -out client.pem -nodes`. `apic describe` shows a `tls` line when a certificate, a CA or `--insecure` applies to the request's host, `run -v` prints the same line, `--json` carries it as `request.tls` (`ca_file`, `cert_file`, `key_file`, `insecure`), and `apic curl` maps it to `--cacert`, `--cert`, `--key` and `--insecure`. OAuth2 token endpoints use the project-wide settings, not a host override. ## curl export `apic curl <id>` maps auth onto curl where curl has an equivalent (and [`apic snippet`](https://apic.sh/cli/#apic-snippet) onto the other languages, in the second table): | Type | curl flags | |---|---| | `bearer` | `-H 'Authorization: Bearer <token>'` | | `basic` | `--user 'user:password'` | | `apikey` | `-H 'X-Api-Key: key'` (or the header named), or `--url-query 'name=key'` for the query form (curl 7.87 or newer) | | `digest` | `--digest --user 'user:password'` | | `aws` | `--aws-sigv4 'aws:amz:<region>:<service>' --user "$AWS_ACCESS_KEY_ID:$AWS_SECRET_ACCESS_KEY"` plus the session token header | | `oauth2` | a placeholder `-H "Authorization: Bearer $TOKEN"` header | | `exec` | `-H "Authorization: Bearer $(command)"` | | Type | httpie | powershell | python | js | go | |---|---|---|---|---|---| | `bearer` | `Authorization:` item | `Authorization` in `-Headers` | `headers={"Authorization": ...}` | `headers` | `req.Header.Set` | | `basic` | `--auth` | a `Basic` header | `auth=(user, password)` | a `Basic` header with `btoa` | `req.SetBasicAuth` | | `apikey` | a header item, or `name==key` for the query | a header, or the key in `-Uri` | `headers`, or `params` | `headers`, or `url.searchParams` | `req.Header.Set`, or the query | | `digest` | `--auth-type=digest --auth` | `-Credential` | `auth=HTTPDigestAuth(...)` | a comment | a comment | | `aws` | a comment | a comment | a comment | a comment | a comment | | `oauth2`, `exec` | the header from `$TOKEN`, with a comment naming the token URL or the command | the same, from `$env:TOKEN` | the same, from `os.environ` | the same, from `process.env` | the same, from `os.Getenv` | ## For agents `describe_request` and `apic describe --json` include `auth` (the spec template) and `auth_source` (`request` or `apic.yaml`). Cached tokens never appear in `list_environments`, `env` or `describe` output, and the credentials apic adds (the `Authorization` header, signatures, tokens) are never part of `run` output: they are set on the wire only. An agent never needs to handle credentials itself: with `aws`, `oauth2` or `exec` configured, `run_request` just works. ## What appears in output Headers you write yourself are shown in `run -v` and `--json`, except that `Authorization`, `Proxy-Authorization`, `Cookie`, `X-Api-Key`, `X-Auth-Token`, `Api-Key`, `X-Amz-Security-Token` and any header whose value came from a secret source (the private env file, `.env`, the session or a capture) are shown as `***`. URL, body and captured values are shown in full so scripts can use them. Pass `--redact` to mask every header value, the body, query-string values and captures, which is the right setting for CI logs that are stored. --- # Testing with Gherkin features URL: https://apic.sh/testing/ apic test runs Gherkin .feature files against your .http requests with a built-in step vocabulary, no Cucumber runtime, and JUnit and cucumber reports. `apic test` runs Cucumber-style `.feature` files against the requests in your `.http` files. There is no Cucumber runtime to install and no step code to write: apic ships a fixed step vocabulary, and each request can declare the phrases that run it. The `.http` files are the API layer; the features describe behaviour on top of it; humans, CI and agents all run the same files with one binary. ```gherkin Feature: Users Background: Given I am logged in Scenario: Fetch a user by id Given a user named "alice" exists When I fetch the user Then the response status is 200 And the response body "$.name" is "alice" And the response body "$.id" is "{{userId}}" ``` ```sh apic test # features/ under the project root apic test features/users.feature --env staging --tags "@smoke && ~@slow" apic test --format junit --output report.xml apic test --json | jq # cucumber JSON report apic test --steps # the vocabulary and your phrases ``` :::tip[Try it offline] `apic demo` writes an example project that includes `features/todos.feature`, so `apic test -C apic-demo` runs a real suite against the bundled fake API with no network access. ::: Standard Gherkin structure works as you would expect: `Background`, `Scenario Outline` with `Examples`, doc strings, data tables and tags. ```gherkin Scenario Outline: Any id echoes back When I fetch user <id> Then the response body "$.args.id" is "<id>" Examples: | id | | 1 | | 999 | ``` ## Phrases on requests Add `# @step` lines to a request. `{name}` placeholders become variables for that request; each matches a quoted string or a bare word. A placeholder written in quotes (`I say "{text}"`) matches only quoted text, spaces included. Placeholder names follow the variable grammar: letters, digits, `_`, `.` and `-`. ```http ### Create a user # @name create-user # @step a user named {name} exists # @assert status == 201 # @capture userId = body.$.id POST {{baseUrl}}/users Content-Type: application/json {"name": "{{name}}"} ### Fetch a user # @name get-user # @step I fetch the user # @step I fetch user {userId} GET {{baseUrl}}/users/{{userId}} Authorization: Bearer {{token}} ``` A phrase does exactly what `I run "<id>"` does: it sends the request, fails the step if any `# @assert` or `# @capture` on it fails, and makes captured values available to later steps. The phrase's parameters apply to that request only; they are not visible to later steps. `apic validate` reports a phrase that could match the same text as another phrase or as a built-in step (for example `# @step I run {x}`, or `I do {x}` next to `I {x} foo`, which both match "I do foo"), since godog would treat such steps as ambiguous. The check is deliberately cautious and may flag a pair that would not collide in practice; rephrase one of them. A phrase may declare at most six parameters. `apic list` and `describe` show phrases. Phrases are matched whatever Gherkin keyword introduces them (`Given`, `When`, `Then`, `And`, `But`). ## Built-in steps Values in quotes may contain `{{variables}}`, which resolve like any other apic variable: environment files, `--var`, captures made earlier in the scenario, and built-ins such as `{{$uuid}}`. ### Setup | Step | Effect | |---|---| | `Given the environment is "staging"` | Switch this scenario to another environment. Variables set by steps, values captured so far, the last response and the session carry over; environment variables come from the new environment. | | `Given the variable "userId" is "42"` | Set a variable. Highest precedence. | | `Given the variables:` + table | Set several. Two columns; a `name | value` header row is optional. Rows apply top to bottom, so a value may reference the rows above it. | ### Running requests | Step | Effect | |---|---| | `When I run "get-user"` | Send a request by id (`name`, `file.http#name` or `file.http#3`). | | `When I run "get-user" with:` + table | Same, with variables set for this request only (rows apply in order, and the table may also supply the target itself). | | `When I run the file "smoke.http"` | Send every request in the file in order; stops at the first failure. | A run step fails when the request cannot be sent (missing variable, network), when any `# @assert` on it fails, or when a `# @capture` finds nothing. The error shows the request line, status, failed assertions and a body excerpt. ### Checking the response The "response" is always the last request sent in the scenario. | Step | Effect | |---|---| | `Then the response status is 200` / `is not 500` | Status code. | | `Then the response is successful` | 2xx. Also `a client error` (4xx), `a server error` (5xx). | | `Then the response body "$.items[0].id" is "7"` | Compare a JSON value. Operators: `is`, `equals`, `is not`, `contains`, `starts with`, `ends with`, `matches` (regular expression). Numbers compare numerically. | | `Then the response header "content-type" contains "json"` | Same operators on a header (case-insensitive name). | | `Then the response cookie "sid" exists` / `is "..."` | A cookie the response set (`Set-Cookie`); same operators, plus `exists` and `does not exist`. With the [cookie jar](https://apic.sh/format/#cookies) on, each scenario has its own jar; `--use-session` shares the stored one. | | `Then the response body "$.error" exists` / `does not exist` | Presence. | | `Then the response body "$.items" has length 3` | Length: a string's characters, an array's elements, an object's keys. | | `Then the response body "$.id" is a number` | Type: `a string`, `a number`, `an integer`, `a boolean`, `an array`, `an object`, `null`. | | `Then the response body "$.items" is empty` / `is not empty` | An empty string, array or object. | | `Then the response body matches the schema "schemas/user.json"` | JSON Schema (2020-12 or draft-07), the path from the project root; `the response body "$.user" matches the schema "…"` checks part of it. A failure names the path in the document and the rule it broke. | | `Then the response body is:` + doc string | Semantic JSON equality: key order and whitespace do not matter, extra keys fail. | | `Then the response body contains:` + doc string | JSON subset: every key in the doc string must be present and equal; arrays must match in length and order; extra keys in the response are fine. | | `Then the response time is under 500 ms` | Round-trip time. | Body paths use the same JSONPath as `# @assert`: `$.a.b`, `$.items[0].id`, `$.items[-1]`, `$.items[1:3]`, `$..id`, `$.items[?(@.done == true)].id`, `.length` or `.#` (count), `$` for the whole body ([all the forms](https://apic.sh/format/#body-paths)). The leading `$.` may be omitted (`"name"` means `$.name`, `"..id"` means `$..id`). Header steps take `"set-cookie.#"` for how many values a header has and `"link[1]"` for one of them. A step's value is quoted, so to check a set of matches, count it or look for one member: `the response body "items[?(@.done == true)].id" contains "c"`. ### Capturing | Step | Effect | |---|---| | `When I capture the response body "$.id" as "userId"` | Store a value for later steps. Also `header` and `cookie`. | `# @capture` lines on requests do this automatically. ## Scenario state Every scenario starts from a clean, in-memory session: nothing captured in an earlier scenario or by `apic run` is visible, and nothing a test does is written to `.apic/session.json`. That keeps scenarios independent and means a `Background` that logs in runs once per scenario. Pass `--use-session` to share the persisted session instead, for example to avoid repeated logins against a slow identity provider. OAuth2 tokens obtained through `# @auth` are cached within a scenario. ## Reports and CI | Flag | Output | |---|---| | `--format pretty` (default) | Coloured, readable; colour off when not a terminal or `NO_COLOR` is set. | | `--format progress` | One character per step. | | `--format junit --output report.xml` | JUnit XML for CI dashboards. | | `--format html --output report.html` | One self-contained HTML file: summary, every feature, scenario and step with its error, light and dark, no external assets. The thing to attach to a CI run or send to someone who does not read JUnit. | | `--format cucumber` or `--json` | Cucumber JSON, the format most reporting tools accept. | Exit codes follow the rest of apic: `0` every scenario passed · `1` at least one failed on an assertion (undefined steps count as failures and are never silently skipped) · `2` a definition problem: no features found, a feature path outside the project root, unknown environment, unknown request, missing variable or bad phrase · `3` a server could not be reached. When a run has both kinds of problem, the definition problem (2) wins, then transport (3), then assertion failures (1). A tag expression that selects no scenarios exits 0 with zero scenarios reported. With `--redact`, step failure messages hide expected and actual values, URLs show masked query values, and every value that came from a secret source (private env file, `.env`, the session, captures) is masked wherever the report mentions it, including in step text, tables and doc strings. In the cucumber JSON report only string values are masked, so numbers and structure are untouched. The report is written when the run completes rather than streamed, so a value captured late in the run is masked in earlier lines too. Values shorter than three characters are not substituted in report text, since masking a lone digit would corrupt the report itself; they are still never printed by error messages. Values passed as `APIC_VAR_*` or `--var` are treated as secrets. ```yaml # GitHub Actions - uses: hungovercoders/apic/setup-apic@v0 - run: apic test -C api --env staging --format junit --output report.xml --redact env: APIC_VAR_password: ${{ secrets.API_PASSWORD }} - uses: dorny/test-reporter@v1 if: always() with: name: API features path: report.xml reporter: java-junit ``` ## For agents The MCP server exposes `run_features {paths?, tags?, env?, vars?, use_session?}`, which returns a summary the agent can act on. Scenarios run in isolated sessions unless `use_session` is true, which shares `.apic/session.json` with `run_request` so captures flow between the tools the way `--use-session` does on the command line: ```json {"ok": false, "exit_code": 1, "scenarios": 4, "passed": 3, "failed": 1, "skipped": 0, "undefined": 0, "failures": [{"feature": "Users", "scenario": "Fetch a user by id", "step": "Then the response status is 200", "status": "failed", "error": "expected status == 200, got \"404\"\n GET https://..."}]} ``` From a shell, `apic test --json` gives the full cucumber report and `apic test --steps --json` lists the vocabulary and phrases, so an agent can write features using only steps that exist. ## Keeping your existing Cucumber If your team already runs cucumber-js, Cucumber-JVM or behave, apic still helps as the transport: a step definition can call `apic run <id> --json --var k=v` and assert on the JSON, so the request definitions live in one place. The built-in runner is simpler when you can adopt it, because it removes the step code and the runtime. ## Limits No custom step code and no scripting; the vocabulary and phrases are the whole language. Scenarios run one at a time. Ad-hoc requests without a `.http` entry are deliberately not supported: the catalogue is the point. --- # Cookbook URL: https://apic.sh/cookbook/ Worked recipes for the jobs that come up most: real APIs, tokens, CRUD flows, polling, uploads and downloads, redirects, secrets in CI, agents and imports. Worked recipes for the jobs that come up most. Each one is self-contained; copy the parts you need. Recipes that use the fake API from `apic demo` can be run as they stand. ## Running against real APIs `examples/` in the repo has three runnable projects, each targeting a real public API instead of `apic demo`'s in-process fake: ```sh apic run auth.http users.http -C examples/httpbin --env dev # basic + bearer, no account needed apic run repo.http -C examples/github --env dev # bearer, needs your own PAT apic run search.http -C examples/spotify --env dev # oauth2 client_credentials, needs your own app ``` For `github` and `spotify`, drop your own credentials into that project's `http-client.private.env.json` first; see `examples/README.md`. ## Log in once and reuse the token everywhere The pattern apic is built around: one request captures the token, every other request uses it, and the value survives between invocations. ```http ### Log in # @name login # @assert status == 200 # @capture token = body.$.access_token POST {{baseUrl}}/auth/login Content-Type: application/json {"user": "{{user}}", "password": "{{password}}"} ### Anything else # @name whoami # @assert status == 200 GET {{baseUrl}}/me Authorization: Bearer {{token}} ``` ```sh apic run login # once apic run whoami # now, tomorrow, in another shell ``` The token lands in `.apic/session.json` under the current environment. `apic session` shows it, `apic session clear` forgets it, and `--no-session` ignores it for one run. If you forget the login, the error says which request would have captured the missing value. To not have to remember it, let the request say what it needs: ```http ### Anything else # @name whoami # @ref login # @assert status == 200 GET {{baseUrl}}/me Authorization: Bearer {{token}} ``` Now `apic run whoami` logs in first when `{{token}}` is missing and goes straight to `/me` when it is not. `# @forceRef login` logs in every time, for a token that must not be reused. See [format.md](https://apic.sh/format/#dependencies). ## Create, read, update, delete in one flow Requests in a file run in order and pass values down the chain, so a full resource lifecycle is one command. ```http ### Create a todo # @name create-todo # @assert status == 201 # @capture todoId = body.$.id POST {{baseUrl}}/todos Authorization: Bearer {{token}} Content-Type: application/json {"title": "Write docs"} ### Read it back # @name get-todo # @assert status == 200 # @assert body.$.title == "Write docs" GET {{baseUrl}}/todos/{{todoId}} Authorization: Bearer {{token}} ### Mark it done # @name update-todo # @assert status == 200 # @assert body.$.done == true PUT {{baseUrl}}/todos/{{todoId}} Authorization: Bearer {{token}} Content-Type: application/json {"done": true} ### Delete it # @name delete-todo # @assert status == 204 DELETE {{baseUrl}}/todos/{{todoId}} Authorization: Bearer {{token}} ``` ```sh apic run todos.http # stops at the first failure apic run todos.http --keep-going # runs everything, then reports ``` A longer version of this file ships with `apic demo`: `apic run login todos.http -C apic-demo --keep-going` runs it offline. Its `not-found` request fails on purpose, to show what a failure looks like. ## A smoke test in CI that never leaks secrets ```yaml # .github/workflows/smoke.yml - uses: hungovercoders/apic/setup-apic@v0 - run: apic validate -C api --format github - run: apic run auth.http smoke.http -C api --env staging --json --redact env: APIC_VAR_password: ${{ secrets.API_PASSWORD }} ``` - `setup-apic` installs a release verified against `checksums.txt`, cached per version and platform, on every runner OS; `with: version: v0.2.0` pins one. Elsewhere, `install.sh` does the same. - `APIC_VAR_<name>` overrides any variable from the shell, so no secret needs to reach the runner's disk. - `--redact` masks header values, bodies, query values and captured values in the stored log. Sensitive headers are masked even without it. - `--json` gives one object per request for whatever reads the log next. - The exit code fails the step: 1 for a failed assertion, 3 for a network error. For a report a person opens rather than a log a tool parses, add `--report` (or `apic test --format html --output`) and upload the file as an artifact; it is one HTML file with no external assets, redacted the same way: ```yaml - run: apic run auth.http smoke.http -C api --env staging --redact --report smoke.html env: APIC_VAR_password: ${{ secrets.API_PASSWORD }} - uses: actions/upload-artifact@v7 if: always() with: name: smoke-report path: smoke.html ``` `apic validate` on its own is a cheap pull-request check: it parses every file, reports duplicate names, bad selectors, unknown auth options and missing body files, and exits 2 if anything is an error. With `--format github` each finding becomes an annotation on the pull request at the exact line and column: ```yaml - run: apic validate -C api --format github ``` ### In a container `ghcr.io/hungovercoders/apic` is the same binary on `scratch`, with the CA bundle it needs for TLS: about 16 MB (about 7 MB to pull), for amd64 and arm64, tagged with the version (`0.2.0` and `v0.2.0`), the minor (`v0.2`) and `latest`. Mount the project at `/work` and pass secrets as `APIC_VAR_*` variables: ```sh docker run --rm -v "$PWD/api:/work" -e APIC_VAR_password \ ghcr.io/hungovercoders/apic run auth.http smoke.http --env staging --json --redact ``` - Files apic writes (`.apic/session.json`, a report) belong to root unless you add `--user "$(id -u):$(id -g)"`. - `apic ui` needs a terminal: `docker run --rm -it …`. - `apic mcp --http 0.0.0.0:8765` with `-p 8765:8765` serves an agent outside the container (set a token, as for any non-loopback address). `apic demo` listens on the container's loopback only, so it is for the container's own use. The image has no shell, so it cannot be a CI system's job image where the job runs a script inside it (GitLab's `image:`, an Azure container job). There, copy the binary into the image you already use: ```dockerfile FROM node:22 COPY --from=ghcr.io/hungovercoders/apic:v0.2 /apic /usr/local/bin/apic ``` or run the installer in the job: ```yaml # .gitlab-ci.yml smoke: image: alpine:3.22 script: - apk add --no-cache curl - curl -fsSL https://raw.githubusercontent.com/hungovercoders/apic/main/install.sh | sh - apic run auth.http smoke.http -C api --env staging --json --redact ``` The image is signed like the release archives; [verifying.md](https://apic.sh/verifying/#verify-the-container-image) has the command. ## AWS API Gateway with SigV4 ```http ### List orders from a private API # @name list-orders # @auth aws service=execute-api region=eu-west-2 # @assert status == 200 GET https://abc123.execute-api.eu-west-2.amazonaws.com/prod/orders Accept: application/json ``` apic signs with your existing credentials: environment variables, a named profile, or an SSO session through the AWS CLI. Nothing apic-specific to configure, and no AWS SDK in the binary. ```sh aws sso login --profile prod AWS_PROFILE=prod apic run list-orders # or: # @auth aws profile=prod ``` Set it once for a whole project in `apic.yaml` instead of on every request: ```yaml auth: default: aws service=execute-api region=eu-west-2 ``` Signing happens after variables are substituted, so a signed request can still use captured values. Other services work the same way with `service=s3`, `service=lambda`, `service=es` and so on. ## OAuth2 client credentials ```http ### Anything behind a machine-to-machine token # @name report # @auth oauth2 tokenUrl={{tokenUrl}} clientId={{clientId}} clientSecret={{clientSecret}} scope="api.read" # @assert status == 200 GET {{baseUrl}}/reports/daily ``` ```json // http-client.env.json { "prod": { "tokenUrl": "https://login.example.com/oauth2/v2.0/token", "clientId": "..." } } // http-client.private.env.json { "prod": { "clientSecret": "..." } } ``` The token is fetched on first use, cached in the session for the environment, reused until a minute before it expires and then refreshed. `apic session` shows what is cached and for how long. This is the same flow for Entra ID, Okta, Auth0, Keycloak and Cognito. See [authentication](https://apic.sh/auth/#oauth2) for the other grants. ## Sign in as yourself ```http ### My repositories, as me # @name my-repos # @auth oauth2 grant=authorization_code authUrl={{authUrl}} tokenUrl={{tokenUrl}} clientId={{clientId}} scope="repo read:user" # @assert status == 200 GET https://api.github.com/user/repos ``` ```json // http-client.env.json { "dev": { "authUrl": "https://github.com/login/oauth/authorize", "tokenUrl": "https://github.com/login/oauth/access_token", "clientId": "Iv1..." } } ``` Run `apic run my-repos` once from a terminal: a browser opens on the provider's sign-in page, and the token comes back through a loopback redirect (register `http://127.0.0.1:<port>/callback` with the app, with `redirectPort=` on the directive when the provider wants the exact port). From then on the cached token, refreshed while its refresh token lasts, serves `--json`, agents and CI alike; only a fresh sign-in needs the terminal again. ## A token from any CLI When the credential comes from a tool rather than a flow: ```yaml # apic.yaml auth: allowExec: true ``` ```http # @auth exec gcloud auth print-identity-token GET {{baseUrl}}/internal/health ``` `exec` is off unless the project opts in, because a request file that runs commands deserves a deliberate yes. ## Poll until something is ready Say what "ready" looks like and how long to wait for it: ```http ### Wait for the job # @name job-status # @retry 30 2s # @assert status == 200 # @assert body.$.state == done GET {{baseUrl}}/jobs/{{jobId}} ``` `apic run job-status` sends the request until both assertions pass or thirty attempts are spent, printing a line per failed attempt, and exits 1 if the job never gets there. `retry:` in `apic.yaml` or `--retry "30 2s"` applies the same policy to every request without its own; see [format.md](https://apic.sh/format/#retries). When the condition is not one assertion can express, the shell still works, with the request kept in the file where everyone can see it: ```sh until apic run job-status --json | jq -e '.response.body.state == "done"' >/dev/null; do sleep 2 done ``` Or assert the state and let a retry loop use the exit code: ```http ### Job status # @name job-status # @assert body.$.state == done GET {{baseUrl}}/jobs/{{jobId}} ``` ```sh for i in $(seq 1 30); do apic run job-status && break; sleep 2; done ``` ## Upload a file A multipart form, the way the editors write it: the boundary in the header, each part between delimiter lines, and a file part whose content is a `< file` reference. apic sends the file's bytes, not the text. ```http ### Upload a report with a title # @name upload-report # @assert status == 201 # @assert body.$.files[0].filename == report.pdf POST {{baseUrl}}/upload Content-Type: multipart/form-data; boundary=WebAppBoundary --WebAppBoundary Content-Disposition: form-data; name="title" Quarterly report for {{user}} --WebAppBoundary Content-Disposition: form-data; name="file"; filename="report.pdf" Content-Type: application/pdf < ./report.pdf --WebAppBoundary-- ``` Text parts are templates, so `{{user}}` resolves as anywhere else. `apic curl upload-report` prints the same upload as `--form-string` and `-F file=@report.pdf` options, and `apic validate` fails when the part file is missing. The demo API's `POST /upload` echoes the parts back, so `apic demo` gives you something to try this against. When the whole body is a file rather than a form, the reference stands alone: ```http ### Upload a payload written by something else # @name import-batch # @assert status == 202 POST {{baseUrl}}/batches Content-Type: application/json < ./payload.json ``` `<` sends the file as it is. `<@` substitutes `{{variables}}` inside it first, which is handy for a fixture with an id or a timestamp in it: ```http <@ ./templated-payload.json ``` Paths are relative to the `.http` file, and `apic validate` fails if the file is missing. ## Download a file A `>>` line after the body saves the response body, bytes as they came, so a CSV export or an image lands on disk intact: ```http ### Daily report # @name daily-report # @assert status == 200 # @assert header.content-type contains text/csv GET {{baseUrl}}/reports/daily.csv >>! ./fixtures/daily.csv ``` `>>` creates the file and fails if it exists; `>>!` overwrites. The path is relative to the `.http` file and stays inside the project; the run says `↳ saved to fixtures/daily.csv`. For a one-off without editing the file: ```sh apic run daily-report --output /tmp/daily.csv ``` A binary body is summarised in the output (`binary body · 12 KB · image/png`) rather than printed, and under `--json` it travels as base64 with `"body_encoding": "base64"`. A saved file is created `0600` when a secret (a private variable, a captured token, a credential) went into the request, since the response may carry one back. ## Follow, or do not follow, redirects Redirects are followed by default. To assert on the redirect itself: ```http ### The redirect itself, not its destination # @name redirect-raw # @no-redirect # @assert status == 302 # @assert header.location contains /status/200 GET {{baseUrl}}/redirect ``` ## Give one slow endpoint more time ```http ### A report that takes a while # @name daily-report # @timeout 90s # @assert status == 200 GET {{baseUrl}}/reports/daily ``` A per-request `# @timeout` beats `--timeout`, which beats `timeout:` in `apic.yaml`, which defaults to 30 seconds. ## Two environments, one command ```json { "$shared": { "userId": 42 }, "dev": { "baseUrl": "https://dev.example.com" }, "staging": { "baseUrl": "https://stg.example.com" } } ``` ```sh for env in dev staging; do apic run smoke.http --env "$env" --keep-going || echo "$env failed" done ``` Each environment keeps its own captured values, so a token from `dev` is never sent to `staging`. In the [terminal UI](https://apic.sh/tui/), <kbd>e</kbd> switches between them. ## Run one request for every row ```csv id,name 7,alice 8,bob ``` ```http ### Update a user # @name update-user # @assert status == 200 # @assert body.$.name == {{name}} PATCH {{baseUrl}}/users/{{id}} Content-Type: application/json {"name": "{{name}}"} ``` ```sh apic run update-user --data users.csv --keep-going --report users.html ``` Each row is one iteration, its columns variables, so the assertion checks each user against its own row. Iterations do not share captures unless `--data-share-session`; see [Data-driven runs](https://apic.sh/cli/#data-driven-runs). ## Describe behaviour, then test it ```http ### Create a user # @name create-user # @step a user named {name} exists # @assert status == 201 # @capture userId = body.$.id POST {{baseUrl}}/users Content-Type: application/json {"name": "{{name}}"} ``` ```gherkin Feature: Users Scenario: A new user can be fetched Given I am logged in And a user named "alice" exists When I run "get-user" Then the response status is 200 And the response body "$.name" is "alice" ``` ```sh apic test # everything under features/ apic test --tags "@smoke && ~@slow" apic test --format junit --output report.xml # for CI ``` `apic test --steps` prints the built-in vocabulary plus the phrases this project declares. Full guide: [testing with Gherkin](https://apic.sh/testing/). ## Hand the API to an agent ```sh claude mcp add api -- apic mcp --dir ./api --env dev ``` The agent gets `list_requests`, `describe_request`, `run_request`, `run_file`, `list_environments`, `clear_session`, `run_features`, `validate_project` and `curl_request`, plus each `.http` file as a readable resource. Assertion failures come back as `ok: false` rather than tool errors, so the agent can reason about them. For an agent that only runs shell commands, paste the snippet from [the agents guide](https://apic.sh/agents/) into your `AGENTS.md` or `CLAUDE.md`. ## Drive it from a Taskfile ```yaml tasks: api: desc: Run an API request, e.g. task api -- get-user --env staging dir: api cmds: - apic run {{.CLI_ARGS}} api:check: desc: Validate the request files and run the smoke flow dir: api cmds: - apic validate - apic run smoke.http --env {{.ENV}} --json ``` Keep `dir:` on every apic task so they share one session. More patterns in [the Taskfile guide](https://apic.sh/taskfile/). ## Start from a curl command Every API's docs have a curl example; paste it and get a named request: ```sh apic import --curl 'curl -X POST https://api.example.com/todos \ -H "Content-Type: application/json" \ -d "{\"title\": \"x\"}"' --into todos.http --name create-todo ``` The host becomes `{{baseUrl}}` when the environment has one, `-u` becomes `# @auth basic`, `-F` becomes a multipart body, and anything apic cannot carry (`-o`, `--retry`, an unknown flag) is a note on stderr rather than a failure. On a Mac, `pbpaste | apic import --curl - --into todos.http` takes the command straight from the clipboard. ## Migrate a Postman collection ```sh apic import My-API.postman_collection.json -o api --postman-env staging.postman_environment.json apic validate -C api apic list -C api ``` Folders become files, requests keep their names in kebab-case, the collection's variables land in `$shared` and each environment export becomes an environment, secrets in the private file. Bearer, basic, AWS and OAuth2 client-credentials auth become `# @auth` lines, an API key becomes its header, and the simple `pm.test` checks (`to.have.status`, `pm.expect(jsonData.x).to.eql(...)`, header checks) become `# @assert` lines, with `pm.environment.set("token", jsonData.token)` becoming `# @capture`. What has no equivalent, pre-request scripts and the rest of the test scripts, is printed as `note` lines so nothing is lost silently; the [comparison](https://apic.sh/comparison/#against-postman) says what to do instead. ## Start from an OpenAPI document ```sh apic import openapi.yaml -o api --env-name dev apic validate -C api apic list -C api ``` You get one `.http` file per tag, a named request per operation, example bodies built from the schemas, and an env file with the server URL. Treat it as a first draft: add `# @capture`, `# @assert` and `# @auth` where they matter. --- # Using apic from an AI agent URL: https://apic.sh/agents/ Drive an API from an AI agent with apic: the shell contract, stable --json output, exit codes, the error catalogue, the MCP server and the Agent Skill. apic is designed so an agent can drive an API with the same files a human uses in their editor. Three integration styles are available. ## 1. Shell (works with any agent that can run commands) Put this in the project's `AGENTS.md` or `CLAUDE.md`: ```markdown ## Calling the API Requests live in `api/*.http` and are run with `apic` (install: see README). - `apic list --json`: every request with id, method, URL and description - `apic describe <id> --json`: variables the request needs and whether it is ready - `apic run <id> --json`: send it; prints one JSON object with `ok`, `request`, `response`, `captures`, `asserts` - `apic run <id> --body-only`: just the response body, for piping to jq - `apic run <file>.http --json`: run a whole file in order as a flow (NDJSON) - `apic run <id> --var name=value`: override a variable - `apic run <id> --env staging`: pick an environment from http-client.env.json - `apic curl <id>`: the equivalent curl command; `apic snippet <id> --lang python` the same in HTTPie, PowerShell, Python, JavaScript or Go - `apic test --json`: run the Gherkin features in features/; `apic test --steps --json` lists the steps you may use - `apic validate --json`: parse every file and report problems before running anything - `apic run <id> --dry-run --json`: the request as it would be sent, resolved, without sending it; look before a call that changes something - `apic run <id> --assert '<expr>' --capture name=selector`: try a check or a selector for one run before writing it into the file - `apic fmt <file>.http#<id>`: format the one request you added and nothing else - `apic run <id> --json --body-limit 8k`: a bounded body, marked `body_truncated`; `apic select <id> body.$.<path>` reads any part of the whole response afterwards without sending again Exit codes: 0 ok, 1 assertion failed, 2 usage/parse/missing variable, 3 network. On exit 2 or 3 with --json, stderr holds one object `{"error": {"code", "message", "hint", ...}}`: branch on `error.code` (E101 missing variable, E201 unknown request, E301 could not connect, ...), not on the message; https://apic.sh/errors/ explains each code. Values captured with `# @capture` (like a login token) persist in `.apic/session.json`, so run `login` once and dependent requests will find the token. A request that declares `# @ref login` runs login by itself when the token is missing. If a request reports a missing variable, the error says which request captures it. ``` The `--json` shape is stable: ```json { "ok": true, "request": {"name": "get-user", "file": "users.http", "line": 10, "method": "GET", "url": "https://...", "headers": {"Accept": "application/json"}}, "response": {"status": 200, "status_text": "OK", "headers": {"content-type": "application/json"}, "body": {"id": 42}, "duration_ms": 87, "size": 412}, "captures": {"email": "a@b.c"}, "asserts": [{"expr": "status == 200", "pass": true, "actual": "200", "expected": "200"}] } ``` `response.body` is parsed JSON when the body is JSON, otherwise a string; a body that is not text comes as base64 with `"body_encoding": "base64"` beside it, and `saved_to` says where a `>> file` line wrote it. `errors` appears only when something failed, as a list of messages. `request.auth` names the auth type applied (`aws`, `oauth2` and so on) without exposing credentials, and sensitive request headers are shown as `***`; see [auth.md](https://apic.sh/auth/). URL, body and captures are real values so an agent can chain them, and `set-cookie` is masked in the response headers. When the output is going into a stored log rather than to an agent, add `--redact`, which masks the response body and headers as well as the request — so a redacted run is for logs, not for chaining. A session usually looks like this: ```console $ apic list --json | jq -r '.requests[] | "\(.id)\t\(.method) \(.url)"' login POST {{baseUrl}}/auth/login whoami GET {{baseUrl}}/me $ apic describe whoami --json | jq '{ready, missing: [.variables[] | select(.missing) | .name]}' {"ready": false, "missing": ["token"]} $ apic run login --json | jq '{ok, captured: .captures}' {"ok": true, "captured": {"token": "mock-token"}} $ apic run whoami --json | jq '{ok, status: .response.status, body: .response.body}' {"ok": true, "status": 200, "body": {"email": "alice@example.com"}} ``` The agent never has to guess: `describe` says what is missing and which request provides it, and the token persists, so `login` is run once rather than before every call. When `whoami` declares `# @ref login`, even that step goes away: `apic run whoami --json` prints `login`'s object and then `whoami`'s, and `describe` reports `"ready": true` with `"ref_runs": true` on the token. ## 2. MCP (Claude Code, Cursor, Windsurf, any MCP client) `apic mcp` serves the project over stdio, or over HTTP for an agent that is not on the same machine. Register it once, in the repository, so every clone has it: ```sh apic mcp install -C ./api --env dev # writes .mcp.json, which Claude Code reads apic mcp install --to .cursor/mcp.json # Cursor reads the same shape from here ``` `apic init` writes the same `.mcp.json` into a new project. The file is what you would write by hand, and any MCP client takes it: ```json {"mcpServers": {"api": {"command": "apic", "args": ["mcp", "--dir", "api", "--env", "dev"]}}} ``` ```sh claude mcp add api -- apic mcp --dir ./api --env dev # per machine instead ``` A client that installs servers from a catalogue finds apic in the [MCP registry](https://registry.modelcontextprotocol.io/) as `io.github.hungovercoders/apic`: the `ghcr.io/hungovercoders/apic` image running `apic mcp` with the project mounted at `/work`. Tools exposed: | Tool | Purpose | |---|---| | `list_requests` | ids, methods, URL templates, descriptions, captures, asserts | | `describe_request {name, env?}` | variables and sources, `ready` flag | | `run_request {name, env?, vars?}` | send one request; returns the same JSON as `apic run --json`, with any `# @ref` dependencies nested under `ran_first` | | `run_file {file, env?, vars?, keep_going?}` | run a file as a flow | | `list_environments {env?}` | environments and effective variables (secrets masked) | | `clear_session {env?, all?}` | forget captured values and cookies | | `run_features {paths?, tags?, env?, vars?, use_session?}` | run Gherkin features; returns pass/fail counts and the failing steps. Scenarios are isolated unless `use_session` shares `.apic/session.json` with the other tools (see [testing.md](https://apic.sh/testing/)) | | `validate_project {}` | parse every `.http` file and report problems with file, line, column and code, without sending anything; the same shape as `apic validate --json`. For an agent that just edited a file | | `curl_request {name, env?, vars?, raw?, lang?}` | the equivalent curl command (or with `lang`, HTTPie, PowerShell, Python, JavaScript or Go), `{"id", "lang", "command"}`, with credentials as shell placeholders and values masked unless `raw` is set; a missing variable is an error naming it, as for `apic curl` | Each `.http` file is also exposed as a resource so the agent can read the definitions. Only the project's own `.http` and `.rest` files can be read this way: any other path is refused, so `http-client.private.env.json`, `.env` and `.apic/session.json` are never served to the agent even though they sit inside the project. The readable set is checked against the project on each read, so a file added after the server started can be read (it is not listed until the server restarts). Assertion failures return `ok: false` rather than a tool error; transport and usage problems return an error the agent can act on: the text is the message followed by `(E101 missing variable: <hint>)`, and the structured content is the same `{"error": {…}}` object the CLI writes. ## 3. A skill (Claude Code, Codex, Cursor, any agent that loads skills) The `AGENTS.md` paragraph above costs a few hundred tokens on every turn, whether or not the task touches the API. A skill is the same briefing loaded on demand: the agent sees one line describing when it applies and reads the rest only when a task involves `.http` files or an API call. [`skills/`](https://github.com/hungovercoders/apic/tree/main/skills) in the repository holds a pack of three, in the [Agent Skills](https://agentskills.io) format every major agent reads, and the binary carries a copy: | Skill | When the agent reads it | |---|---| | `apic` | A task touches `.http` files or calls an API: the workflow (validate, list, describe, run, chain), the `--json` shape and exit codes, the error codes to branch on, the rules for writing a request and where secrets belong, and when to use `apic test` or the MCP tools instead. `references/cheatsheet.md` is the [cheat sheet](https://apic.sh/cheatsheet/) with absolute links, generated by `task skill` so the two cannot drift. | | `api-design` | The user is building an API or an endpoint, writing or reviewing an OpenAPI document, or choosing routes, status codes or an error format: the design decisions, each proved by a request `apic run` sends or a mock `apic mock` serves, with a contract skeleton and a review checklist in its references. | | `api-security` | The user asks whether their API is secure, adds authentication, or hardens an endpoint before release: the OWASP API Security Top 10 as checks, authentication, authorisation, input and resource limits, headers, secrets and logging, each written as an `.http` request or Gherkin scenario that fails while the control is missing, with a bank of ready checks and a release checklist in its references. | ```sh apic skill install # the apic skill, into .claude/skills and .agents/skills of the project apic skill install --all # the whole pack apic skill install --user --all # the same under your home directory, once, for every project apic skill install --skill api-security # exactly this skill apic skill # print the apic skill, for an agent that can run commands apic skill api-security # print another npx skills add hungovercoders/apic # the same files from the repository, for the agents the CLI finds ``` The `apic` skill is apic's own text about using apic, so `apic init` and `apic skill install` write it by default. `api-design` and `api-security` are opinions about the reader's API (which status codes, which error shape, which checks), so a project opts into them with `--all` or `--skill`, and the tests in each skill's `evals/` (run by `task agent:eval`) measure whether they change what an agent does. Commit the directories. `--to <dir>` picks another location, and copying a directory by hand works wherever your agent reads skills from. Use them with the MCP server or without: the `apic` skill tells the agent to prefer the tools when they exist, and the other two tell it to prove every design and security decision with a request the project keeps. `apic skill --json` gained a `skills` array naming the pack; `name` and `files` are unchanged. ## Errors Every error has a stable code from the [error catalogue](https://apic.sh/errors/), and an agent should read the code rather than parse the message, whose wording may improve between releases: | Where | What | |---|---| | `apic … --json`, exit 2 or 3 | one `{"error": {"code", "title", "message", "hint", "exit", "url"}}` object on stderr, plus `suggestions` (the closest known names, best first) when an unknown request or environment is near one that exists; stdout carries only results | | `apic run --json`, a request that could not be sent | its result has `"ok": false` and the same object as `error`, beside `errors` | | MCP tool error | the object as structured content; the text ends with `(code title: hint)` | The codes an agent meets most, and what to do: | Code | Do | |---|---| | [E101](https://apic.sh/errors/#e101) missing variable | the message names the request that captures it: run that, or pass `vars` | | [E201](https://apic.sh/errors/#e201) unknown request | retry with the first of `suggestions` when there are any; otherwise `list_requests` (or `apic list --json`) and pick an id | | [E103](https://apic.sh/errors/#e103) request file has errors | `validate_project` and fix what it reports | | [E301](https://apic.sh/errors/#e301)–[E303](https://apic.sh/errors/#e303) network | report to the user; the server is down, slow or untrusted, and retrying the same thing will not help | ### Over HTTP ```sh apic mcp --http 127.0.0.1:8765 APIC_MCP_TOKEN=$(openssl rand -hex 16) apic mcp --http 0.0.0.0:8765 --dir ./api ``` `--http` serves the MCP streamable HTTP transport instead of stdio, for a hosted agent, a shared development box, or a container that also runs the API under test. The same tools and resources are exposed. Bound to the loopback interface it needs nothing else; bound anywhere else it refuses to start without a bearer token (`--token`, or `APIC_MCP_TOKEN`), which every client must send as `Authorization: Bearer <token>`. The server runs the project's requests with the project's credentials, so that rule is not optional. Point the client at `http://<host>:<port>/`: ```json {"mcpServers": {"api": {"type": "http", "url": "http://127.0.0.1:8765/", "headers": {"Authorization": "Bearer <token>"}}}} ``` ## Writing requests as an agent The format is plain text, so an agent can add requests too. Keep to the subset in [the format guide](https://apic.sh/format/), give every request a `# @name`, add an `# @assert status == 200` and run `apic validate` afterwards. `apic init` writes a correct skeleton to start from, and the [cheat sheet](https://apic.sh/cheatsheet/) fits in a prompt. When the task comes with an OpenAPI document and no running API, `apic import openapi.yaml -o api` writes the requests and `apic mock openapi.yaml` serves the document's declared responses on localhost, so `apic run <id> -C api --var baseUrl=http://localhost:8090` proves the requests match the contract before the backend exists; a `Prefer: code=404` header line asks for a documented error response. It proves nothing about the API itself, so point `baseUrl` at the real one when there is one. See [`apic mock`](https://apic.sh/cli/#apic-mock). ## Reading these docs as an agent Every page here is also available as plain text, so an agent can read the documentation without parsing HTML: - [llms.txt](https://apic.sh/llms.txt) lists every page with a one-line summary, in reading order. Fetch it first and follow only the links the task needs. - [llms-full.txt](https://apic.sh/llms-full.txt) is every page in one Markdown document, for an agent that would rather load the whole manual once. Inside a project, `apic skill` prints the same briefing the Agent Skill installs, and `apic <command> --help` is always current for the binary on the machine, whichever docs version the agent read. `apic version --json` names that binary's release, and the [changelog](https://apic.sh/changelog/) says what each release added or changed, so an agent can tell whether a command the docs describe is in the binary it has. --- # Editors URL: https://apic.sh/editors/ What VS Code, JetBrains IDEs and Neovim give you for .http files, and what the apic extension and apic lsp add on top. apic runs the `.http` format that editors already understand, and everything it adds is a comment. So the same file is clickable in VS Code, JetBrains IDEs and Neovim, and runnable by apic from the terminal, CI and an agent. This page is what each editor gives you and what apic's own extension adds. ## VS Code Two extensions, and they cooperate: - **REST Client** (`humao.rest-client`) provides the `http` language, the highlighting, and "Send Request" above each request. apic's `# @` lines are comments to it, so a file with assertions and captures still sends. - **apic** (`hungovercoders.apic`, on the [Marketplace](https://marketplace.visualstudio.com/items?itemName=hungovercoders.apic) and [Open VSX](https://open-vsx.org/extension/hungovercoders/apic)) layers apic on top. **Run**, **Describe** and **Copy as curl** sit above every request, and **Run file as flow** at the top of a file; a run goes through apic's runner, assertions, captures and `# @ref` dependencies included, marks the request line `✓ 200 · 12 ms`, and opens a response panel beside the editor with the body highlighted, every assertion's actual against expected, and the captures. `apic validate` runs when a request file, `apic.yaml` or an env file changes on disk, and its findings land in the Problems panel at the exact span with quick fixes for a mistyped directive, a duplicate name and a missing body file. An **apic** view in the activity bar lists every request by file with a ready/not-ready icon and shows the session (captured values and cookies) for the environment in effect, which the status bar names and **apic: Select environment** changes. **Format Document** goes through `apic fmt`, and the bundled schemas validate `apic.yaml` (with the YAML extension), the env files and the session file. Typing `# @` offers every directive with its shape filled in, `{{` offers the variables of the environment in effect (source alongside, secrets masked), the session's captures, the built-ins and `<name>.response.…` references, `# @assert` and `# @capture x =` offer the selectors and, after `body.$.`, the keys of that request's last response; hovering a `{{placeholder}}` shows its value and source, or which request captures it. The **Test Explorer** lists every `.feature` file under the project's test paths with its scenarios and example rows, runs them through `apic test` in the environment in effect (a tag expression on request), and shows a failing step's message at its line; a `# @step` line in a request file says how many scenarios use its phrase and opens them. With **apic.languageServer.enable** on, the diagnostics, completion and hover come from [`apic lsp`](#any-editor-with-an-lsp-client) instead, so problems show as you type rather than on save. Install it from the Marketplace or Open VSX (search for **apic**), or from the `.vsix` attached to a `vscode-v*` entry on the [releases page](https://github.com/hungovercoders/apic/releases?q=vscode): ```sh code --install-extension apic-<version>.vsix ``` To build it from the repository instead: `cd editors/vscode && npm ci && npm run package`. ## JetBrains IDEs The built-in HTTP Client sends the same files. It ignores apic's directives, and apic ignores its `> {% … %}` response handlers (and says so in `apic validate`). Both read `http-client.env.json` and `http-client.private.env.json`, so one set of environments serves both. ## Neovim [kulala.nvim](https://github.com/mistweaverco/kulala.nvim) sends `.http` files and reads the same env files. Add `apic lsp` (below) for problems, completion and hover as you type, and apic's terminal UI is the natural companion: `apic ui` opens the request under the cursor in `$EDITOR` with <kbd>o</kbd> and reloads when you return. ## Any editor with an LSP client `apic lsp` is a language server on stdin/stdout, built into the binary, so any editor with an LSP client gets what the VS Code extension has: - **Diagnostics as you type**: `apic validate`'s findings for the buffer you are editing, saved or not, at the exact span and with their codes, and for `apic.yaml` and the env files when they change on disk. - **Completion**: directives after `# @`, variables inside `{{` (the environment's, with their source and secrets masked, the session's captures, the built-ins and `<name>.response.…` references), selectors after `# @assert` and `# @capture x =`, and after `body.$.` the keys of that request's last response (from a run in the editor, or the [response history](https://apic.sh/cli/#apic-history)); operators, `# @auth` types and `# @ref` targets. - **Hover** on a `{{placeholder}}`: its value and where it came from, or which request captures it. - **Code lenses** above every request: Run, Describe and curl, run by the server, with a one-line result and the full report in the editor's log (curl with its credentials as shell placeholders, as `apic curl --redact` prints it). - **Formatting** through `apic fmt`. The project is found from each file: the nearest directory holding `apic.yaml` or an `http-client` env file, without leaving the workspace folder. The environment is `env` in the client's initialisation options, else `--env` on the command, else `apic.yaml`'s `env:`; the [CLI reference](https://apic.sh/cli/#apic-lsp) lists the other options. **Neovim** (0.11 or later): ```lua vim.filetype.add({ extension = { http = "http", rest = "http" } }) vim.lsp.config("apic", { cmd = { "apic", "lsp" }, filetypes = { "http" }, root_markers = { "apic.yaml", "http-client.env.json", ".git" }, init_options = { env = "dev" }, -- optional }) vim.lsp.enable("apic") ``` **Helix**, in `languages.toml`: ```toml [language-server.apic] command = "apic" args = ["lsp"] [[language]] name = "http" scope = "source.http" file-types = ["http", "rest"] roots = ["apic.yaml", "http-client.env.json"] comment-token = "#" language-servers = ["apic"] ``` **JetBrains IDEs**: install the [LSP4IJ](https://plugins.jetbrains.com/plugin/23257-lsp4ij) plugin, add a new language server with the command `apic lsp`, and map it to the file name patterns `*.http` and `*.rest`. The built-in HTTP Client keeps sending the requests; the server adds apic's diagnostics, completion and hover beside it. **Emacs** with Eglot: ```elisp (add-to-list 'eglot-server-programs '((restclient-mode http-mode) . ("apic" "lsp"))) ``` **Zed** starts language servers from extensions, and there is no apic extension for Zed yet; the terminal commands below work there today. ## Any editor Highlight or not, the terminal is always there: ```sh apic run get-user # the request under your cursor, by name apic validate --format text # problems with line and column apic ui # the terminal UI, next to the editor ``` --- # Using apic with Taskfile URL: https://apic.sh/taskfile/ Make Task the front door for an apic project: tasks that run requests and flows, with the environment and secrets handled in one place. If your team already runs things with [Task](https://taskfile.dev), keep it. apic is a plain CLI with clean exit codes, so Task becomes the front door and the `.http` files hold the requests. ## Before and after A curl-based task carries the whole request inline and has to be edited to change a header: ```yaml get-user: cmds: - curl -sS -H "Authorization: Bearer $TOKEN" "$BASE_URL/users/$ID" ``` With apic the request lives in `api/users.http`, where an editor can also send it and an agent can read it: ```http ### Fetch a user # @name get-user # @assert status == 200 GET {{baseUrl}}/users/{{userId}} Authorization: Bearer {{token}} ``` and the task is a one-line reference: ```yaml get-user: dir: api cmds: - apic run get-user --var userId={{.ID}} ``` ## Patterns ### Passthrough `task api -- get-user --env staging` behaves exactly like `apic run`: ```yaml version: "3" tasks: api: desc: Run an API request, e.g. task api -- get-user --env staging dir: api cmds: - apic run {{.CLI_ARGS}} ``` ### Named tasks with an environment variable ```yaml vars: ENV: '{{.ENV | default "dev"}}' tasks: login: desc: Log in and store the token for later tasks dir: api cmds: - apic run login --env {{.ENV}} user: desc: task user ID=42 [ENV=staging] dir: api cmds: - apic run get-user --env {{.ENV}} --var userId={{.ID}} smoke: desc: Run every request in smoke.http; fails if any assertion fails dir: api cmds: - apic run smoke.http --env {{.ENV}} ``` Run `task login ENV=staging` once, then `task user ID=7 ENV=staging` as often as you like. The token lives in apic's session, so you do not need `deps: [login]` on every task. Add it only where a stale token would be confusing: ```yaml user: deps: [login] cmds: - apic run get-user --var userId={{.ID}} ``` ### Piping output into other tasks ```yaml order-id: dir: api cmds: - apic run create-order --body-only | jq -r .id > .order-id order-status: dir: api deps: [order-id] cmds: - apic run get-order --var orderId=$(cat .order-id) --json | jq .response.status ``` Or let apic keep the value instead of a temp file, with `# @capture orderId = body.$.id` on `create-order`; then `get-order` can use `{{orderId}}` directly. ### Checks in CI ```yaml api:check: desc: Validate request files and run the smoke flow dir: api cmds: - apic validate - apic run smoke.http --env {{.ENV}} --json ``` Secrets arrive through the environment rather than files: ```sh APIC_VAR_password="$API_PASSWORD" task api:check ENV=staging ``` ### curl fallback For a machine that has Task and curl but not apic: ```yaml api:curl: desc: Print the curl for a request, e.g. task api:curl -- get-user dir: api cmds: - apic curl {{.CLI_ARGS}} ``` ### Installing apic from a task ```yaml api:install: desc: Install apic if it is missing status: [command -v apic] cmds: - curl -fsSL https://raw.githubusercontent.com/hungovercoders/apic/main/install.sh | sh ``` Add `deps: [api:install]` to the api tasks and a fresh checkout works with one `task`. ## Things to watch - **Working directory.** `.apic/session.json` lives where apic runs. Set `dir: api` on every apic task so all of them share one session. - **Quoting.** Task runs commands through its own shell interpreter. Quote `--var` values containing spaces or `#`: `--var 'note=hello world'`. - **Exit codes.** Task fails a task on non-zero exit, so a failed assertion (exit 1) fails the task, which is what you want in CI. Use `ignore_error: true` on a task if you only want the report. - **JSON in Task output.** Task prefixes nothing to stdout, so `task api -- get-user --json | jq` works. Use `silent: true` to hide the echoed command line. ## The repo's own Taskfile `Taskfile.yml` at the root of this repository builds apic and drives four example projects with it: `task example:demo` runs the bundled offline demo end to end, `task example` runs `examples/httpbin` against httpbin.org (`ENV=dev`, needs network), and `task example:github` / `task example:spotify` run the GitHub and Spotify examples, each of which needs your own credentials in that project's `http-client.private.env.json` first. All are small working instances of these patterns. --- # Migrating from Postman URL: https://apic.sh/migrate/postman/ Move a Postman collection to apic in one command: what apic import translates, what it lists as untranslated, and how to finish by hand. A Postman collection comes across in one command. `apic import` turns folders into `.http` files, requests into named requests, environments into `http-client.env.json`, auth helpers into `# @auth`, and the simple `pm.test` and `pm.environment.set` lines into `# @assert` and `# @capture`. What it cannot translate it lists, request by request, so nothing is dropped silently. ## How the concepts map | Postman | apic | |---|---| | Collection | a project: a directory with `.http` files and `apic.yaml` | | Folder | a `.http` file (`todos.http`; nested folders join with `-`) | | Request | a `### ` block with `# @name` | | Collection variables | `$shared` in `http-client.env.json` | | Environment | an environment in `http-client.env.json`; secret values go to `http-client.private.env.json` | | `{{var}}`, `:id` path variables, `{{$guid}}` | `{{var}}`, `{{id}}`, `{{$uuid}}` | | Auth tab (bearer, basic, digest, AWS, API key, OAuth2 client credentials and password) | `# @auth` on the request; the collection's own auth becomes `auth.default` in `apic.yaml` | | `pm.test` with `pm.response.to.have.status(200)` | `# @assert status == 200` | | `pm.expect(json.x).to.eql(1)`, `.include`, `.exist`, `.be.true` | `# @assert body.$.x == 1`, `contains`, `exists`, `== true` | | `pm.expect(pm.response.responseTime).to.be.below(500)` | `# @assert duration < 500` | | `pm.environment.set("token", json.token)` | `# @capture token = body.$.token`, kept in the session between runs | | Collection runner | `apic run file.http` (a flow, in order) or `apic run a b c` | | Runner with a data file | `apic run --data rows.csv` | | Newman | `apic run --json`, `--report report.html`, or `apic test --format junit` for features | | Pre-request script | not translated: see [what does not carry over](#what-does-not-carry-over) | ## Import a collection The collection below has what most real ones have: a log-in request whose test stores the token, a request that uses it, a pre-request script and a secret in the environment. It targets `apic demo`, so every step here runs as written (start it with `apic demo` in another terminal). <!-- learn --> ```sh cat > shop.postman_collection.json <<'EOF' { "info": {"name": "Shop", "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", "event": [{"listen": "test", "script": {"exec": [ "pm.test(\"logged in\", () => pm.response.to.have.status(200));", "const body = pm.response.json();", "pm.environment.set(\"token\", body.access_token);" ]}}], "request": {"method": "POST", "url": "{{baseUrl}}/auth/login", "header": [{"key": "Content-Type", "value": "application/json"}], "body": {"mode": "raw", "raw": "{\"user\": \"alice\", \"password\": \"{{password}}\"}"}}} ]}, {"name": "Todos", "item": [ {"name": "List todos", "event": [ {"listen": "prerequest", "script": {"exec": ["pm.variables.set(\"started\", Date.now());"]}}, {"listen": "test", "script": {"exec": [ "pm.test(\"ok\", () => pm.response.to.have.status(200));", "pm.test(\"fast\", () => pm.expect(pm.response.responseTime).to.be.below(1000));" ]}}], "request": {"method": "GET", "url": "{{baseUrl}}/todos", "auth": {"type": "bearer", "bearer": [{"key": "token", "value": "{{token}}"}]}}} ]} ] } EOF cat > local.postman_environment.json <<'EOF' {"name": "local", "values": [{"key": "password", "value": "s3cret", "type": "secret", "enabled": true}]} EOF apic import shop.postman_collection.json -o shop --postman-env local.postman_environment.json --force ``` ```text wrote shop/auth.http wrote shop/todos.http wrote shop/http-client.private.env.json wrote shop/apic.yaml wrote shop/http-client.env.json (baseUrl = http://localhost:8089) 2 request(s) generated; run `apic list` to see them note list-todos: pre-request script: not translated; compute values with --var or a # @ref request instead ``` Each folder is a file, and the tests became directives: ```http # auth — generated by `apic import` from "shop.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": "alice", "password": "{{password}}"} ``` ```http # todos — generated by `apic import` from "shop.postman_collection.json". Edit freely. ### List todos # @name list-todos # @auth bearer {{token}} # @assert status == 200 # @assert duration < 1000 GET {{baseUrl}}/todos ``` The password went to `http-client.private.env.json`, which belongs in `.gitignore`; `apic.yaml` makes `local` the default environment. ## Run it, and let the token look after itself In Postman the runner went through the requests in order so the token was set before it was used. apic keeps captured values in a session between commands, so running `log-in` once is enough; better still, say that `list-todos` needs it, and apic runs `log-in` first whenever the token is missing: <!-- learn --> ```sh cat > shop/todos.http <<'EOF' # todos — generated by `apic import` from "shop.postman_collection.json". Edit freely. ### List todos # @name list-todos # @ref log-in # @auth bearer {{token}} # @assert status == 200 # @assert duration < 1000 GET {{baseUrl}}/todos EOF apic session clear -C shop apic run list-todos -C shop | grep -E '^(POST|GET|✓|↳)' ``` ```text POST http://localhost:8089/auth/login ✓ status == 200 ↳ token = mock-token ↳ ran log-in first (# @ref) GET http://localhost:8089/todos ✓ status == 200 ✓ duration < 1000 ``` `apic run log-in list-todos -C shop` still runs both in order, and `apic run todos.http -C shop` runs a whole folder's worth as a flow. ## A bigger example: Postman Echo Postman's own Postman Echo collection, for the [postman-echo.com](https://postman-echo.com) service, is a good test of an import, since it uses query parameters, form bodies, basic and digest auth and plenty of tests. Fork it from Postman's public workspace, export it as Collection v2.1, then: ```sh apic import "Postman Echo.postman_collection.json" -o echo apic list -C echo apic validate -C echo apic run -C echo "$(ls echo/*.http | head -1 | xargs basename)" --keep-going ``` Read the `note` lines the import prints: they are the tests and scripts that need a decision (see the next section). The requests themselves run against the live service as they are. ## What does not carry over - **Scripts.** apic has no JavaScript, [deliberately](https://apic.sh/comparison/#deliberately-not-planned). Every script line the importer does not recognise is printed as a `note` and listed under `unsupported` in `--json`. Their usual jobs have homes: a computed value comes from `--var`, `APIC_VAR_*` or a built-in such as `{{$timestamp}}`; a token from `# @auth` or a `# @ref` request; a check from `# @assert`; anything else from a shell script around `apic run --json`. - **Browser OAuth2 flows, NTLM and Hawk.** Reported by the importer. apic does OAuth2 client credentials, password, device code and authorization code with PKCE: see [authentication](https://apic.sh/auth/). - **Mock servers, monitors, workspaces and sharing.** Postman's hosted features have no equivalent; the project is files in git. - **Collection v1.** Export as v2.1. ## Checklist - [ ] `apic import collection.json -o api --postman-env env.json` for each environment - [ ] Read every `note` line and decide: `# @assert`, `# @capture`, `--var`, or delete - [ ] Add `http-client.private.env.json` and `.apic/` to `.gitignore` - [ ] Put `# @ref log-in` on the requests that need the token - [ ] `apic validate` is clean and `apic fmt --check` passes - [ ] `apic run <file>.http --json` in CI in place of Newman See also: [`apic import`](https://apic.sh/cli/#apic-import) in the CLI reference, the [`.http` format](https://apic.sh/format/), and [lesson 9](https://apic.sh/learn/09-import-export/) of the course, which imports an OpenAPI document too. --- # Migrating from Bruno URL: https://apic.sh/migrate/bruno/ Move a Bruno collection to apic: how the concepts map, block by block, with a worked example. Bruno and apic agree on the important thing: requests are plain files in git. Moving across is a translation of one text format into another, block by block. There is no importer yet, so this page is the mapping and a worked example; a collection of a few dozen requests takes an afternoon. ## How the concepts map | Bruno | apic | |---|---| | Collection folder with `bruno.json` | a project: a directory with `.http` files and `apic.yaml` | | A `.bru` file (one request) | a `### ` block with `# @name` in a `.http` file; put a folder's requests in one file | | `meta { name, seq }` | `# @name`; order in the file is the run order | | `get { url }`, `post { url, body: json }` | the request line: `POST {{baseUrl}}/todos` | | `headers { … }` | header lines under the request line | | `body:json { … }`, `body:form-urlencoded`, `body:multipart-form` | the body after a blank line; [multipart](https://apic.sh/format/#multipart-uploads) for file parts | | `auth:bearer`, `auth:basic`, `auth:awsv4`, `auth:digest`, `auth:oauth2` | `# @auth bearer …`, `basic`, `aws`, `digest`, `oauth2`; see [authentication](https://apic.sh/auth/) | | Collection-level auth in `collection.bru` | `auth.default` in `apic.yaml` | | `environments/local.bru` `vars { … }` | the `local` environment in `http-client.env.json` | | `vars:secret [ … ]` | `http-client.private.env.json`, kept out of git | | `.env` and `{{process.env.NAME}}` | `.env` in the project root, read as variables, or `{{$dotenv NAME}}` | | `vars:pre-request { x: 1 }` | a file variable `@x = 1`, or `--var x=1` | | `vars:post-response { token: res.body.access_token }` | `# @capture token = body.$.access_token`, kept between runs | | `assert { res.status: eq 200 }` | `# @assert status == 200` | | `res.body.items: length 3`, `isString`, `isNumber`, `isEmpty`, `isNull` | `# @assert body.$.items length == 3`, and the same predicates | | `eq`, `neq`, `gt`, `gte`, `lt`, `lte` | `==`, `!=`, `>`, `>=`, `<`, `<=` | | `contains`, `startsWith`, `endsWith`, `matches` | the same names | | `isDefined`, `isUndefined` | `exists`, `not exists` | | `notContains`, `notMatches`, `in`, `between`, `isTruthy`, `isJson` | no direct form: assert the positive case, or two bounds for `between` | | `bru run --env local` | `apic run <file>.http --env local` | | `bru run --csv-file-path rows.csv` | `apic run --data rows.csv` | | `--reporter-json`, `--reporter-junit`, `--reporter-html` | `apic run --json`, `apic test --format junit`, `apic run --report report.html` | | Script, tests and docs blocks | see [what does not carry over](#what-does-not-carry-over) | ## A worked example Two Bruno requests against the demo API, a log-in that keeps the token and a list that uses it: ```text meta { name: Log in seq: 1 } post { url: {{baseUrl}}/auth/login body: json } body:json { {"user": "alice", "password": "{{password}}"} } vars:post-response { token: res.body.access_token } assert { res.status: eq 200 } ``` ```text meta { name: Open todos seq: 2 } get { url: {{baseUrl}}/todos?done=false auth: bearer } auth:bearer { token: {{token}} } assert { res.status: eq 200 res.body: isArray res.body[0].done: eq false } ``` and `environments/local.bru`: ```text vars { baseUrl: http://localhost:8089 } vars:secret [ password ] ``` In apic, both requests go in one file, the environment in `http-client.env.json` and the secret in the private file (with `apic demo` running in another terminal): <!-- learn --> ```sh mkdir -p from-bruno cat > from-bruno/http-client.env.json <<'EOF' { "local": { "baseUrl": "http://localhost:8089" } } EOF cat > from-bruno/http-client.private.env.json <<'EOF' { "local": { "password": "s3cret" } } EOF printf 'env: local\n' > from-bruno/apic.yaml cat > from-bruno/todos.http <<'EOF' ### Log in # @name log-in # @assert status == 200 # @capture token = body.$.access_token POST {{baseUrl}}/auth/login Content-Type: application/json {"user": "alice", "password": "{{password}}"} ### Open todos # @name open-todos # @ref log-in # @auth bearer {{token}} # @assert status == 200 # @assert body.$ isArray # @assert body.$[0].done == false GET {{baseUrl}}/todos?done=false EOF apic validate -C from-bruno apic run todos.http -C from-bruno | tail -4 ``` ```text ✓ 1 file, 2 requests, no problems ✓ log-in 200 1 ms ✓ open-todos 200 0 ms 2 passed · 2 requests · 1 ms ``` `# @ref log-in` is the part Bruno has no word for: `open-todos` now logs in by itself when there is no token, so `apic run open-todos` works on its own, and the token survives to the next command. ## What does not carry over - **Scripts and tests blocks.** `script:pre-request`, `script:post-response` and `tests` are JavaScript; apic has none, [deliberately](https://apic.sh/comparison/#deliberately-not-planned). Most of what they do is a `# @capture`, a `# @assert` or a `--var`; the rest belongs in a shell script around `apic run --json`. - **`docs` blocks.** Use the `### title` line (it becomes the request's description in `apic list`) or `#` comments. - **gRPC and WebSocket requests.** apic is HTTP only. - **The Bruno app.** `apic ui` is a terminal UI; the [VS Code extension](https://apic.sh/editors/) sends `.http` files with a click, as JetBrains and Neovim do. ## Checklist - [ ] One `.http` file per Bruno folder, a `### ` block per `.bru` file, in `seq` order - [ ] `environments/*.bru` to `http-client.env.json`, secrets to `http-client.private.env.json` - [ ] `vars:post-response` to `# @capture`, `assert` to `# @assert` - [ ] Collection auth to `auth.default` in `apic.yaml` - [ ] `# @ref` on requests that need a token - [ ] Every script and tests block rewritten or dropped on purpose - [ ] `apic validate` is clean and `apic fmt --check` passes - [ ] `bru run` in CI replaced with `apic run --json` or `apic test` See also: the [`.http` format](https://apic.sh/format/), the [assertion operators](https://apic.sh/cheatsheet/#assertion-operators) and [apic compared with Bruno](https://apic.sh/comparison/#against-bruno). --- # Migrating from Hurl URL: https://apic.sh/migrate/hurl/ Move Hurl files to apic: how sections become # @ directives, what changes for the better, and what does not carry across. Hurl and apic are close cousins: one binary each, plain-text files, captures and assertions. The move is mostly mechanical. A Hurl entry's sections become `# @` directives above an `.http` request, and the files become ones VS Code, JetBrains and Neovim can send with a click. One thing changes for the better on the way: captures persist between runs, so a single named request can run on its own with the token kept from an earlier run. ## How the concepts map | Hurl | apic | |---|---| | A `.hurl` file | a `.http` file; `apic run file.http` runs it top to bottom as a flow | | An entry (request plus response section) | a `### ` block with `# @name`, so it can also run alone | | `HTTP 200` | `# @assert status == 200` | | `[Captures]` `token: jsonpath "$.token"` | `# @capture token = body.$.token` | | `header "Location"`, `cookie "sid"` | `header.location`, `cookie.sid` | | `jsonpath "$.items[0].id"` | `body.$.items[0].id` (filters, slices and `..` too; see [body paths](https://apic.sh/format/#body-paths)) | | `status`, `duration`, `body` | `status`, `duration`, `body` | | `[Asserts]` `jsonpath "$.id" == 42` | `# @assert body.$.id == 42` | | `==`, `!=`, `>`, `>=`, `<`, `<=` | the same | | `contains`, `startsWith`, `endsWith`, `matches` | the same names | | `exists`, `not exists` | the same | | `isString`, `isInteger`, `isBoolean`, `isCollection`, `isEmpty` | the same, with `isArray` or `isObject` for `isCollection` | | `jsonpath "$.items" count == 3` | `# @assert body.$.items length == 3` | | `[Options]` `retry: 10` `retry-interval: 2000` | `# @retry 10 2s` | | `[Options]` `delay: 500` | `# @sleep 500ms` | | `[Options]` `http2: true` | `GET https://… HTTP/2` on the request line | | `[Options]` `insecure: true`, `cacert`, `cert`, `key` | `--insecure`, or `tls:` in `apic.yaml` and `--cacert`, `--cert`, `--key` | | `[BasicAuth]` | `# @auth basic user pass` | | `[FormParams]`, `[MultipartFormData]` | a urlencoded body, or a [multipart body](https://apic.sh/format/#multipart-uploads) | | `{{name}}` with `--variable name=value` | `{{name}}` with `--var name=value` | | `--variables-file vars.env` | an environment in `http-client.env.json`, or `.env` | | `HURL_name` environment variables | `APIC_VAR_name` | | `--test`, `--glob` | `apic run a.http b.http --keep-going` | | `--report-junit`, `--report-html`, `--report-json` | `apic test --format junit` for features; `apic run --report report.html`; `apic run --json` | | `--json` (one line per file) | `apic run --json` (one object per request) | ## A worked example A Hurl file against the demo API: ```text POST http://localhost:8089/auth/login {"user": "alice", "password": "{{password}}"} HTTP 200 [Captures] token: jsonpath "$.access_token" GET http://localhost:8089/todos?done=false Authorization: Bearer {{token}} HTTP 200 [Asserts] header "X-Total-Count" exists jsonpath "$" count >= 1 jsonpath "$[0].done" == false jsonpath "$[0].id" isString ``` The same two requests in apic (with `apic demo` running in another terminal). The host moves into the environment, each entry gets a name, and each section line becomes a directive: <!-- learn --> ```sh mkdir -p from-hurl cat > from-hurl/http-client.env.json <<'EOF' { "local": { "baseUrl": "http://localhost:8089" } } EOF cat > from-hurl/todos.http <<'EOF' ### Log in # @name login # @assert status == 200 # @capture token = body.$.access_token POST {{baseUrl}}/auth/login Content-Type: application/json {"user": "alice", "password": "{{password}}"} ### The open todos # @name open-todos # @assert status == 200 # @assert header.x-total-count exists # @assert body.$ length >= 1 # @assert body.$[0].done == false # @assert body.$[0].id isString GET {{baseUrl}}/todos?done=false Authorization: Bearer {{token}} EOF apic run todos.http -C from-hurl --env local --var password=s3cret | tail -4 ``` ```text ✓ login 200 1 ms ✓ open-todos 200 0 ms 2 passed · 2 requests · 1 ms ``` Hurl adds `Content-Type: application/json` to a JSON body by itself; in a `.http` file, write the header, since editors send exactly what the file says. Then, because the token was captured into the session, the second request runs on its own, with no login in the same run: <!-- learn --> ```sh apic run open-todos -C from-hurl --env local | tail -1 ``` ## What does not carry over - **XPath, `sha256`, `md5` and the filter chain** (`jsonpath "$.x" split "," nth 1`). apic's selectors are JSONPath, headers, cookies, status, duration and the raw body; a check that needs a transformation goes in a shell script around `apic run --json`. - **`[Options]` for curl internals** such as `compressed`, `path-as-is` or `unix-socket`. apic is not built on libcurl. - **`--test` reports per file.** apic reports per request; `--keep-going` and the summary line give the same pass/fail picture. - **Hurl's own format.** apic reads `.http` only; the two formats are close enough that a search-and-replace does most of it. ## Checklist - [ ] One `.http` file per `.hurl` file, a `### ` block and `# @name` per entry - [ ] `HTTP <code>` to `# @assert status == <code>` - [ ] `[Captures]` to `# @capture`, `[Asserts]` to `# @assert`, `jsonpath "$…"` to `body.$…` - [ ] Hosts to `{{baseUrl}}` in `http-client.env.json`; `--variables-file` to an environment - [ ] `[Options] retry` to `# @retry` - [ ] A `Content-Type` header on each JSON body - [ ] `apic validate` is clean and `apic fmt --check` passes - [ ] `hurl --test` in CI replaced with `apic run *.http --keep-going` See also: the [assertion operators](https://apic.sh/cheatsheet/#assertion-operators), [`# @retry`](https://apic.sh/format/#retries) and [apic compared with Hurl](https://apic.sh/comparison/#against-hurl). --- # Migrating from httpyac URL: https://apic.sh/migrate/httpyac/ Run an httpyac project under apic: what runs unchanged, and how to replace script blocks, ?? tests and the directives apic does not have. httpyac and apic read the same files: `.http` requests separated by `###`, `# @name`, `http-client.env.json` with `$shared`, `.env`, and the same `{{$uuid}}`-style built-ins. Much of an httpyac project runs under apic unchanged, and the two can share a project, httpyac in the editor and apic for agents and CI. What needs changing is httpyac's JavaScript (script blocks and `??` tests) and a handful of directives apic does not have. `apic validate` finds each one with its line and column. ## How the concepts map | httpyac | apic | |---|---| | `###`, `# @name`, request line, headers, body | the same | | `# @ref login`, `# @forceRef login` | the same, including `{{login.response.body.$.token}}` after a `# @ref`; see [dependencies](https://apic.sh/format/#dependencies) | | `{{login.token}}` (a named response's parsed body) | `{{login.response.body.$.token}}`, or `# @capture token = body.$.token` on `login` and `{{token}}` everywhere | | `# @import ./other.http` | not needed: every `.http` file in the project is loaded, and `# @ref` reaches across files | | `?? status == 200` | `# @assert status == 200` above the request line | | `?? header content-type includes json` | `# @assert header.content-type contains json` | | `?? duration < 500` | `# @assert duration < 500` | | `?? body == hello` | `# @assert body == hello` | | `?? js response.parsedBody.id == 42` | `# @assert body.$.id == 42` | | `{{ exports.token = response.parsedBody.token }}` | `# @capture token = body.$.token` | | Other `{{ … }}` script blocks | see [what does not carry over](#what-does-not-carry-over) | | `# @loop for 3`, `# @loop for item of items` | `apic run --data rows.csv`, one run per row | | `# @sleep 1000` (milliseconds) | `# @sleep 1s` (a Go duration) | | `# @timeout 5000` (milliseconds) | `# @timeout 5s` | | `# @no-cookie-jar` | `# @no-cookies`, when the [cookie jar](https://apic.sh/format/#cookies) is on | | `Authorization: Basic user:pass`, `Digest user pass` | `# @auth basic user pass`, `# @auth digest user pass` | | `Authorization: openid client_credentials local`, OAuth2 variables | `# @auth oauth2 …`, or a JetBrains `Security.Auth` block; see [authentication](https://apic.sh/auth/) | | AWS signing variables | `# @auth aws region=… service=…` | | `httpyac send file.http --all` | `apic run file.http` | | `httpyac send file.http --name login` | `apic run login` | | `--env dev`, `--var key=value` | `--env dev`, `--var key=value` | | `--json`, `--junit` | `apic run --json`, `apic test --format junit` | | `.httpyac.json`, `httpyac.config.js` | `apic.yaml` for the settings apic has | | `env/*.env` files per environment | environments in `http-client.env.json`; a root `.env` is still read | ## A worked example An httpyac file with the usual mix: an import, a file-level script, a `??` test, a response handler that exports the token, a `# @ref` and a loop: ```http # @import ./shared.http {{ exports.started = Date.now(); }} ### # @name login POST {{baseUrl}}/auth/login Content-Type: application/json {"user": "alice", "password": "{{password}}"} ?? status == 200 {{ exports.token = response.parsedBody.access_token; }} ### # @name todos # @ref login # @loop for 3 GET {{baseUrl}}/todos Authorization: Bearer {{token}} ?? status == 200 ``` apic reads the directives it knows, warns about the ones it does not, and refuses the script blocks, which it cannot tell from a malformed request: ```text todos.http:1:3: warning: unknown directive @import (ignored) (unknown-directive) todos.http:4:3: error: expected a header (`Name: value`) or a blank line before the body, got "exports.started = Date.now();" (bad-header) todos.http:5:1: error: expected a header (`Name: value`) or a blank line before the body, got "}}" (bad-header) todos.http:23:3: warning: unknown directive @loop (ignored) (unknown-directive) ✗ 1 file, 3 requests, 2 errors, 2 warnings ``` The `??` lines and the script after the body are worse: they sit where the body is, so they would be sent as part of it. Take them out as you turn them into directives. The same file, for apic (with `apic demo` running in another terminal): <!-- learn --> ```sh mkdir -p from-httpyac cat > from-httpyac/http-client.env.json <<'EOF' { "$shared": { "baseUrl": "http://localhost:8089" }, "local": {} } EOF cat > from-httpyac/.env <<'EOF' password=s3cret EOF cat > from-httpyac/todos.http <<'EOF' ### # @name login # @assert status == 200 POST {{baseUrl}}/auth/login Content-Type: application/json {"user": "alice", "password": "{{password}}"} ### # @name todos # @ref login # @assert status == 200 GET {{baseUrl}}/todos Authorization: Bearer {{login.response.body.$.access_token}} EOF apic validate -C from-httpyac apic run todos -C from-httpyac --env local --no-session | grep -E '^(POST|GET|✓)' ``` ```text ✓ 1 file, 2 requests, no problems POST http://localhost:8089/auth/login ✓ status == 200 GET http://localhost:8089/todos ✓ status == 200 ``` `# @ref login` meant the same in both tools, and still does: `todos` reads `login`'s response, so `login` runs first. The file keeps working in httpyac, which reads `# @assert` as an unknown comment and `.env` and `http-client.env.json` as before. The `# @loop for 3` became nothing here. To run a request once per row of data, give `apic run` a CSV file: <!-- learn --> ```sh printf 'page\n1\n2\n3\n' > from-httpyac/pages.csv cat >> from-httpyac/todos.http <<'EOF' ### # @name todos-page # @ref login # @assert status == 200 GET {{baseUrl}}/todos?page={{page}}&limit=1 Authorization: Bearer {{login.response.body.$.access_token}} EOF apic run todos-page -C from-httpyac --env local --no-session --data from-httpyac/pages.csv | tail -1 ``` ## What does not carry over - **JavaScript.** Script blocks, response handlers, `?? js` tests with logic, hooks and plugins. apic has no scripting, [deliberately](https://apic.sh/comparison/#deliberately-not-planned); what the scripts did is usually a `# @capture`, an `# @assert` or a `--var`, and the rest belongs in a shell script around `apic run --json`. - **`# @import`.** Not needed for requests (the whole project is loaded), but a variable defined in an imported file must move to `http-client.env.json` or to the file that uses it. - **gRPC, WebSocket, MQTT, AMQP and server-sent events.** apic is HTTP only. - **`# @loop`.** `apic run --data` covers a loop over data; a loop over a computed list needs a shell loop. - **httpyac's config files.** `apic.yaml` has the settings apic has: default environment, timeout, retry, proxy, TLS, auth defaults. ## Checklist - [ ] `apic validate` over the project, and every error and warning dealt with - [ ] `??` tests to `# @assert` above the request line - [ ] Response handlers that export values to `# @capture` (or `{{name.response…}}` after a `# @ref`) - [ ] Script blocks removed, their jobs moved to directives, `--var` or a shell script - [ ] `# @sleep` and `# @timeout` values given units - [ ] `Authorization:` shorthands to `# @auth` - [ ] `# @loop` to `apic run --data` - [ ] `apic fmt --check` passes, and the files still open in httpyac See also: the [`.http` format](https://apic.sh/format/), [response references](https://apic.sh/format/#response-references) and [apic compared with httpyac](https://apic.sh/comparison/#against-httpyac). --- # Migrating from curl and Taskfile URL: https://apic.sh/migrate/curl/ Turn curl commands in a Taskfile, Makefile or wiki into named .http requests, with Task kept as the front door. This is the move apic was made for: requests that live as curl commands in a Taskfile, a Makefile, a wiki page or shell history, with the token pasted in by hand. Each command becomes a named request in a `.http` file that editors can send, agents can read and CI can run, and Task, if you use it, stays as the front door. ## How the concepts map | curl and a Taskfile | apic | |---|---| | A curl command | a `### ` block with `# @name` in a `.http` file | | `-X POST`, `-H`, `-d`, `-F`, `-u` | the request line, headers, body, a multipart body, `# @auth basic` | | `$BASE_URL`, `$TOKEN` in the shell | `{{baseUrl}}` from `http-client.env.json`, `{{token}}` captured by a login request | | `TOKEN=$(curl … \| jq -r .token)` | `# @capture token = body.$.access_token`, kept in the session between commands | | `curl -f`, `\| grep`, `\| jq -e` to check a result | `# @assert status == 200`, `# @assert body.$.id exists` | | `-k`, `--cacert`, `--cert`, `-x` | `--insecure`, `--cacert`, `--cert`, `--proxy`, or `tls:` and `proxy:` in `apic.yaml` | | A task per request | `task api -- <name>`, one passthrough task (see [Taskfile](https://apic.sh/taskfile/)) | | `task --list` | `apic list`, with methods, URLs and descriptions | | Copy the command from the wiki | `apic curl <name>` prints it back, runnable as printed; `--redact` for one that is safe to paste into a log | ## Turn each command into a request `apic import --curl` reads a curl command, in either quote style and with backslash continuations, and appends a request to a file. With `apic demo` running in another terminal: <!-- learn --> ```sh mkdir -p from-curl cat > from-curl/http-client.env.json <<'EOF' { "local": { "baseUrl": "http://localhost:8089" } } EOF printf 'env: local\n' > from-curl/apic.yaml apic import -C from-curl --into auth.http --name login \ --curl 'curl -s -X POST http://localhost:8089/auth/login -H "Content-Type: application/json" -d '"'"'{"user":"alice","password":"s3cret"}'"'"'' apic import -C from-curl --into todos.http --name list-todos \ --curl 'curl -s http://localhost:8089/todos -H "Authorization: Bearer mock-token"' cat from-curl/auth.http from-curl/todos.http ``` ```text added login to auth.http added list-todos to todos.http ### POST /auth/login # @name login # @assert status == 200 POST {{baseUrl}}/auth/login Content-Type: application/json {"user":"alice","password":"s3cret"} ### GET /todos # @name list-todos # @assert status == 200 GET {{baseUrl}}/todos Authorization: Bearer mock-token ``` The host became `{{baseUrl}}` because the environment's `baseUrl` prefixes it, and each request got a status check. What the importer cannot know is where the secrets come from: the password and the token are still pasted in. ## Take the secrets out Move the password to the private env file, which stays out of git, capture the token from the login response, and let `list-todos` log in by itself when it has none: <!-- learn --> ```sh cat > from-curl/http-client.private.env.json <<'EOF' { "local": { "password": "s3cret" } } EOF cat > from-curl/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": "{{password}}"} EOF cat > from-curl/todos.http <<'EOF' ### List todos # @name list-todos # @ref login # @assert status == 200 GET {{baseUrl}}/todos Authorization: Bearer {{token}} EOF apic session clear -C from-curl apic run list-todos -C from-curl | grep -E '^(POST|GET|✓|↳)' ``` ```text POST http://localhost:8089/auth/login ✓ status == 200 ↳ token = mock-token ↳ ran login first (# @ref) GET http://localhost:8089/todos ✓ status == 200 ``` ## Keep Task as the front door A Taskfile of curl commands: ```yaml version: "3" tasks: login: cmds: - curl -s -X POST "$BASE_URL/auth/login" -H "Content-Type: application/json" -d "{\"user\":\"alice\",\"password\":\"$PASSWORD\"}" | jq -r .access_token > .token todos: cmds: - curl -sf "$BASE_URL/todos" -H "Authorization: Bearer $(cat .token)" ``` becomes one task that passes its arguments through, plus named tasks for the ones people type every day: ```yaml version: "3" tasks: api: desc: Run an API request, e.g. task api -- list-todos --env staging dir: from-curl cmds: - apic run {{.CLI_ARGS}} todos: desc: List the todos dir: from-curl cmds: - apic run list-todos ``` The `.token` file, the `jq` and the `-f` are gone: the session holds the token, `# @ref` fetches it, and `apic run` exits non-zero when an assertion fails (1), a request cannot be built (2) or the network fails (3). More patterns are in [Using apic with Taskfile](https://apic.sh/taskfile/). ## And back to curl For the machine with no apic, or a bug report, `apic curl` prints the command again with every variable filled in, so it runs as printed. With `--redact`, header, body and query values are masked (a `# @auth` credential becomes a shell placeholder such as `$TOKEN`), for pasting into a ticket or a log: <!-- learn --> ```sh apic curl list-todos -C from-curl apic curl list-todos -C from-curl --redact ``` ```text curl -sS \ -H 'Authorization: Bearer mock-token' \ 'http://localhost:8089/todos' curl -sS \ -H 'Authorization: ***' \ 'http://localhost:8089/todos' ``` `apic snippet list-todos --lang python` does the same for HTTPie, PowerShell, Python, JavaScript and Go. ## What does not carry over - **Shell logic between commands.** Loops, conditionals and computed values stay in the shell, around `apic run --json`, which prints one JSON object per request for `jq`. - **curl's own output flags** (`-o`, `-w`, `-v`, `--trace`). apic has `-v`, `--json`, `--body-only` and `--output <file>`; the importer notes the flags that change behaviour, such as `-o`, `-w` and `--trace`, and drops `-s`, `-v`, `-i` and `-f` silently. - **Protocols other than HTTP.** apic does not do FTP, SMTP or the rest of what curl speaks. ## Checklist - [ ] `apic import --curl '…' --into <file>.http --name <name>` for each command - [ ] Hosts to `{{baseUrl}}` in `http-client.env.json`, one environment per target - [ ] Passwords and keys to `http-client.private.env.json`; `.apic/` and the private file in `.gitignore` - [ ] Hand-pasted tokens replaced with `# @capture` on the login and `# @ref login` where it is needed - [ ] Checks done with `grep` or `jq -e` moved to `# @assert` - [ ] Taskfile tasks reduced to `apic run <name>` - [ ] `apic validate` is clean and `apic fmt --check` passes See also: [`apic import --curl`](https://apic.sh/cli/#apic-import), [`apic curl`](https://apic.sh/cli/#apic-curl), [`apic snippet`](https://apic.sh/cli/#apic-snippet) and [Using apic with Taskfile](https://apic.sh/taskfile/). --- # CLI reference URL: https://apic.sh/cli/ Every apic command with what it does, its --json output and its exit codes, plus every flag generated from the binary. ``` apic [command] [flags] ``` Each command's section below explains what it does, its JSON and its exit codes; [Commands and flags](#commands-and-flags) at the end is every flag of every command, generated from the binary's own command tree. All commands are non-interactive: apic never prompts. The one exception is `apic ui`, the terminal UI, which refuses to start unless it has a terminal to draw on. Colour is off when stdout is not a terminal, when `NO_COLOR` is set, when `--no-color` is given, or when `--json` is used. ## Global flags | Flag | Meaning | |---|---| | `-C, --dir <path>` | Project root holding the `.http` files and env files. Default `.`. Relative `.http` paths on the command line are resolved against it. | | `-e, --env <name>` | Environment from `http-client.env.json`. Defaults to `env:` in `apic.yaml`, else none (only `$shared` values apply). An unknown name is an error listing the known ones. | | `--var name=value` | Override a variable. Repeatable. Highest precedence. | | `--json` | Machine-readable output. See each command for the shape. | | `--no-color` | Disable colour. | | `--no-session` | Do not read or write `.apic/session.json`; with cookies on, the jar stays in memory for the one command. | | `--cookies` | Keep a cookie jar: cookies a response sets are sent with later requests to the same site and stored per environment in `.apic/cookies.json`. Same as `cookies: true` in `apic.yaml`. See [format.md](https://apic.sh/format/#cookies). | | `--timeout <duration>` | Request timeout, e.g. `10s`. Default 30s or `timeout:` in `apic.yaml`. `# @timeout` on a request wins. | | `--insecure` | Skip TLS certificate verification. Reported as `tls.insecure` in `--json` and by `describe`. | | `--cacert <pem>` | Trust the certificates in this PEM file in addition to the system roots, for an API behind a private CA. | | `--proxy <url>` | Send every request through this proxy: an `http`, `https`, `socks5` or `socks5h` URL, or a bare `host:port` for HTTP. Beats `proxy:` in `apic.yaml` and `HTTP_PROXY`/`HTTPS_PROXY`. Credentials go in the URL's userinfo and are shown as `***` wherever the proxy is reported. | | `--no-proxy` | Send every request directly, ignoring `--proxy`, `apic.yaml` and the environment. | | `--cert <pem>`, `--key <pem>` | Present a client certificate (mTLS); the key defaults to the `--cert` file. These override `tls:` in `apic.yaml` and the env files' `SSLConfiguration`. See [auth.md](https://apic.sh/auth/#tls-and-client-certificates). | | `--redact` | Mask values on both sides of the exchange in `run` output: every request header value, the request body, query-string values, captured values, the response body, every response header value, and the `actual`/`expected` of every assertion. Status, timing, size and pass/fail survive, so a stored CI log still says what failed. Sensitive request headers (`Authorization`, `Cookie`, API-key headers, and any header whose value came from a secret source) and sensitive response headers (`Set-Cookie`, `WWW-Authenticate`) are masked even without it. | ## Exit codes | Code | Meaning | |---|---| | 0 | Success. For `run`, every assertion and capture passed. For `validate`, no errors. | | 1 | `run`: at least one assertion or capture failed. | | 2 | Usage error: unknown command or request, parse error in a `.http` file, unknown environment, missing variable, bad `--var`. `validate` with errors. | | 3 | Transport error: DNS, connection refused, TLS failure, timeout. | Ctrl-C during a run stops it where it is: a flow prints its summary so far, the session and the history keep what the completed requests captured and returned, `--report` is still written, and the exit is 3 with [E305](https://apic.sh/errors/#e305). A second Ctrl-C ends the process at once. The servers (`demo`, `mcp`, `lsp`) stop cleanly and exit 0. Errors are printed to stderr prefixed with `error:`; stdout stays clean for piping. Every error has a stable code. Under the message come the [error catalogue](https://apic.sh/errors/)'s hint, unless the message already names an apic command to run, and a line with the code and where the catalogue explains it; both are dim on a terminal and plain in a log: ```text error: me.http:1: missing variable {{token}}: pass --var token=... 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 ``` A request id or an environment that matches nothing but is close to one that exists gets a guess, in the message and, under `--json`, as `suggestions`: ```text error: no request named "get-usr"; did you mean get-user? (run `apic list` for every id) E201 unknown request · see https://apic.sh/errors/#e201 ``` Under `--json` the error is instead one JSON object on stderr, so a script branches on `error.code` rather than the wording: ```json {"error":{"code":"E101","title":"missing variable","message":"me.http:1: missing variable\n {{token}}: …","hint":"Pass it with --var name=value, …","exit":2,"url":"https://apic.sh/errors/#e101"}} ``` A `run` result for a request that could not be sent carries the same object as `error`, beside the `errors` list of messages. The exit status follows from the code: E1xx and E2xx exit 2, E3xx exit 3. ## Request targets Several commands take a target: | Target | Meaning | |---|---| | `get-user` | The request with `# @name get-user`. An error if the name is used in more than one file. | | `users.http` | Every request in the file, in order. | | `users.http#get-user` | A named request in a specific file. | | `users.http#3` | The third request in the file. Unnamed requests are listed with this id. | Files are found by walking the project root for `*.http` and `*.rest`, skipping hidden directories, `node_modules`, `vendor` and `testdata`. `apic.yaml` can narrow this with `dir: api`. ## apic run ``` apic run <target>... [-v] [--body-only] [--keep-going] [--retry "<n> [interval]"] [--no-retry] [--output <file>] [--report <file.html>] [--data rows.csv|rows.json|- [--data-share-session]] [--assert <expr>]... [--capture <name=selector>]... [--dry-run] ``` Sends requests and reports status, timing, body, captures and assertions. Several targets run in the order given. More than one request is a flow: it stops at the first failed assertion, failed capture or transport error unless `--keep-going` is set, and prints a pass/fail summary. Captured values are available to later requests in the same run, and are saved to `.apic/session.json` for the current environment (unless `--no-session` or the request has `# @no-session`). A request with `# @ref login` runs `login` first when a value it needs is missing, and one with `# @forceRef login` runs it first every time; see [format.md](https://apic.sh/format/#dependencies). The terminal output shows the dependency's report first, under `↳ ran login first (# @ref)`. A request with `# @retry 10 2s` is sent again until its assertions pass, up to ten times, two seconds apart; see [format.md](https://apic.sh/format/#retries). Each failed attempt prints `attempt 1/10 · <first failed assertion>` as it happens, and the report of the attempt that counted ends its status line with `· 3 attempts`. Results print as each request finishes, so a flow shows progress. | Flag | Meaning | |---|---| | `-v, --verbose` | Show request headers and body, response headers, and where the time went: `dns 12 ms · connect 18 ms · tls 41 ms · ttfb 60 ms · total 87 ms · new connection`. | | `--body-only` | Print only the response body, pretty-printed when JSON. For piping. | | `--keep-going` | In a flow, continue after a failure. | | `--retry "<n> [interval]"` | Retry policy for requests without `# @retry`: attempts and the wait between them (default `1s`). Overrides `retry:` in `apic.yaml`. | | `--report <file.html>` | Also write a self-contained HTML report of the run: summary, every request with its status, timing, assertions (actual against expected), captures and the request and response headers and bodies, collapsed. Honours `--redact` like the text output and shows a "redacted" badge; sensitive headers are masked either way. Refused when the path is a project file. | | `--no-retry` | Send every request once, ignoring `# @retry`, `--retry` and `apic.yaml`. | | `--output <file>` | Save the response body to this file, relative to the working directory, overwriting: what a `>>! file` line in the request does (see [format.md](https://apic.sh/format/#saving-a-response)). One request only; a flow is refused, and so is a project input as the target. The text output says `↳ saved to <file>` and `--json` carries `saved_to`. | | `--data <file>` | Run the targets once per row: a CSV file whose header row names the variables, or a JSON array of objects; `-` reads stdin. See [Data-driven runs](#data-driven-runs). | | `--data-share-session` | With `--data`, let one iteration's captures reach the next and the session file. | | `--assert <expr>` | Check the response with an expression, as `# @assert` would, for this run only; repeatable. The result lists it after the request's own assertions, and a failure exits 1 like any other. A bad expression is a flag error before anything is sent. Try a check here before writing it into the file. | | `--capture <name=selector>` | Capture a value, as `# @capture` would, for this run only; repeatable. It goes into the result and the session like a directive's capture. | | `--body-limit <size>` | Show at most this much of each response body (`4k`, `64k`, `1m`, or bytes) in the JSON, `--body-only` and the text output, with `"body_truncated": true` beside it; `size` is still the whole body's, and a cut JSON body comes as a string. The response history records the whole body first, so `apic select <id> body.$.<path>` reads any part of it afterwards. For a caller whose context the body goes into. | | `--dry-run` | Resolve each target and print the request that would be sent (method, URL, headers and body, with `-v`'s detail) without sending it: no dependency runs, no auth is applied, nothing is captured. A variable a `# @ref` dependency would capture is left as its `{{placeholder}}` with a warning saying which request the run would send first; any other missing variable is the error a run gives. `--json` prints the run object with `"dry_run": true`, the warnings and no `response`; `--body-only` prints the request body. Refused with `--data`, `--output` and `--report`. | Examples: ```sh apic run login apic run get-user --env staging --var userId=42 apic run auth.http users.http --json apic run get-user --body-only | jq .email ``` `--json` prints one object per request (NDJSON for flows): ```json { "ok": true, "request": { "name": "get-user", "file": "users.http", "line": 10, "method": "GET", "url": "https://dev.example.com/users/42", "headers": {"Accept": "application/json", "Authorization": "Bearer eyJ..."}, "body": "", "auth": "aws" }, "response": { "status": 200, "status_text": "OK", "headers": {"content-type": "application/json"}, "body": {"id": 42, "email": "alice@example.com"}, "duration_ms": 87, "size": 412, "proto": "HTTP/2.0", "timings": {"dns_ms": 12, "connect_ms": 18, "tls_ms": 41, "ttfb_ms": 60, "total_ms": 87, "reused": false} }, "captures": {"email": "alice@example.com"}, "asserts": [ {"expr": "status == 200", "pass": true, "actual": "200", "expected": "200"}, {"expr": "body.$.id == 42", "pass": true, "actual": "42", "expected": "42"} ] } ``` - `request.auth` names the auth type applied, when any; credentials apic adds are never included. - `request.headers` are the headers written in the file, with sensitive values shown as `***` (see `--redact` above). URL, body and captures are shown in full unless `--redact` is set. - `request.body` of a [multipart upload](https://apic.sh/format/#multipart-uploads) is the summary `<multipart: 2 parts, 1 file>` rather than the assembled bytes. - `response.body` is parsed JSON when the body is JSON, otherwise a string. A body that is not text (not valid UTF-8) is its base64 with `"body_encoding": "base64"` beside it, so a download survives `--json` intact. Under `--redact` it is the string `"***"`. - `response.proto` is the protocol the response came over, `HTTP/1.1` or `HTTP/2.0`. `request.http_version` (omitted otherwise) is the version the request line pins, `HTTP/1.1` or `HTTP/2`; see [HTTP version](https://apic.sh/format/#http-version). - `saved_to` (omitted otherwise) is where a `>> file` line or `--output` wrote the body, relative to the project root when inside it. - `response.headers` keys are lower-case; multiple values are joined with `, `. `set-cookie` and `www-authenticate` are always `***`; under `--redact` every value is. - `asserts[].actual` and `asserts[].expected` are `***` under `--redact`, and `expr` keeps only its selector and operator. `pass` and `error` are unaffected. - `errors` (omitted when empty) lists failed captures and other problems. - `warnings` (omitted when empty) lists problems that did not fail the request, such as a [response history](#apic-history) that could not be written. - `ok` is false when any assertion or capture failed, and when a request a `# @ref` ran first failed; `errors` then names it (`@ref login failed`). - `response.timings` breaks `duration_ms` down: name resolution, the TCP connection, the TLS handshake, the wait for the first byte of the response, and the total including the body, with `reused` true when the connection came from an earlier request of the same invocation (a flow's requests share their connections). A reused connection has no DNS, connect or TLS time; redirects and a digest challenge add their hops together. `duration_ms` is unchanged. - `attempts` (omitted when no retry policy applied) is how many times the request was sent; the object describes the last attempt. Attempt lines are not printed under `--json`. - `iteration` (only under [`--data`](#data-driven-runs)) is `{"index": 3, "total": 50, "row": {"id": "7"}}`: which row the object belongs to and the variables it supplied, values `***` under `--redact`. - `skipped` (omitted otherwise) is `"disabled"` for a [`# @disabled`](https://apic.sh/format/#pauses-and-disabled-requests) request that a file's flow did not send: `ok` is true and there is no `response`. Naming the request sends it. - Requests a `# @ref` or `# @forceRef` ran first are printed as objects of their own, before the request that needed them, so there is still exactly one object per request sent. The `ran_first` key is only present in the MCP `run_request` result, where the dependency's result nests under the request's. - When a request could not be sent at all (missing variable, network), the error goes to stderr and the exit code is 2 or 3; in a flow, the earlier results are still printed. ### Data-driven runs ```sh apic run get-user --data users.csv apic run checkout.http --data orders.json --keep-going --report orders.html jq -c '[.[] | {id}]' ids.json | apic run get-user --data - ``` `--data` runs the targets once per row. In a CSV file the header row names the variables (a spreadsheet's byte order mark is ignored); in JSON each object is a row, numbers written without an exponent. The row's values sit at `--var` precedence, over the same names from `--var`, for that iteration only. Each iteration starts from the session as it was when the run began and writes nothing back, so what one iteration captures does not reach the next: fifty users each get their own `{{id}}`, not the last one's. `--data-share-session` runs every iteration on one session instead, which also saves captures to `.apic/session.json` as a plain run does. A token a `# @ref login` fetched is fetched once per iteration without it and once with it. The text output heads each iteration `iteration 3/50 · id=7 name=alice` (the values left out under `--redact`) and ends with `50 of 50 iterations: 49 passed`; each `--json` object carries `iteration`. A failed iteration stops the run unless `--keep-going`, which then runs every row and, as in a flow, every request; the exit code is 1 if any iteration failed. `--output` is refused with `--data`, since it would be overwritten each time; `--report` covers every iteration. ## apic test ``` apic test [path|file.feature]... [--format f] [--output file] [--tags expr] [--stop-on-failure] [--use-session] [--steps] ``` Runs Gherkin feature files against the project's requests with a built-in step vocabulary and the `# @step` phrases declared on requests. Default path is `features/` under the project root, or `test.paths` in `apic.yaml`. Each scenario gets an isolated in-memory session. See [testing.md](https://apic.sh/testing/) for the vocabulary. | Flag | Meaning | |---|---| | `-f, --format` | `pretty` (default), `progress`, `cucumber`, `junit`, `html` (a self-contained report, with `--output`). `--json` selects `cucumber`. | | `-o, --output <file>` | Write the report to a file. | | `-t, --tags <expr>` | Tag expression, e.g. `"@smoke && ~@slow"`. | | `--stop-on-failure` | Stop after the first failed scenario; the remaining scenarios are reported as skipped. | | `--use-session` | Share `.apic/session.json` instead of isolating each scenario. | | `--steps` | Print the vocabulary and this project's phrases (`--json` for machine form) and exit. | Exit codes: `0` all passed · `1` failures or undefined steps · `2` no features, a feature path outside the project, unknown environment, unknown request, missing variable, bad phrase or bad flag · `3` a server could not be reached. Feature paths must lie inside the project root. ## apic ui ``` apic ui [--demo] ``` Opens the [terminal UI](https://apic.sh/tui/): requests on the left, each row carrying its status and round trip once it has run, and preview, response, checks, session and history tabs on the right. <kbd>enter</kbd> runs the selected request, <kbd>f</kbd> runs its file as a flow, <kbd>e</kbd> switches environment, <kbd>J</kbd>/<kbd>K</kbd> scroll the right pane, <kbd>?</kbd> lists every key. | Flag | Meaning | |---|---| | `--demo` | Serve the bundled fake API in-process and open the UI on its example project. Needs no project and no network. | It is the only interactive command, and the only one without `--json`: with `--json`, or when stdout is not a terminal, it exits 2 and points at `apic run` and `apic list` instead. All the other global flags (`-C`, `--env`, `--var`, `--redact`, `--timeout`, `--insecure`, `--no-session`) work as usual. ## apic list ``` apic list [pattern] ``` Every request in the project in file order: id, method, URL template, `file:line` and description, grouped by file. A pattern keeps only the requests whose id, URL, file or description contains it, case-insensitively. `--json`: ```json { "root": "/abs/path/api", "requests": [ {"id": "login", "name": "login", "method": "POST", "url": "{{baseUrl}}/auth/login", "file": "auth.http", "line": 6, "description": "Log in and keep the token", "captures": ["token"], "asserts": 1} ] } ``` `name` is omitted for unnamed requests; `id` is then `file.http#N`. `steps` lists the request's `# @step` phrases and `refs` its `# @ref` and `# @forceRef` targets, when it has any. `disabled` is true for a request marked [`# @disabled`](https://apic.sh/format/#pauses-and-disabled-requests), which a flow skips. A pattern filters the `requests` array; the shape does not change. ## apic describe ``` apic describe <target> ``` Shows one request's method, URL template, headers, body, every variable it references with the source it resolved from, its captures and asserts, and whether it is ready to run. Missing variables come first, with the request that captures them if there is one. A missing variable that a `# @ref` of the request supplies does not make it unready: the line says the request runs first. `--json`: ```json { "name": "whoami", "id": "whoami", "file": "auth.http", "line": 16, "description": "Uses the token captured by login", "method": "GET", "url_template": "{{baseUrl}}/bearer", "url": "https://httpbin.org/bearer", "headers": {"Authorization": "Bearer {{token}}"}, "variables": [ {"name": "token", "source": "missing", "missing": true, "captured_by": "login", "ref_runs": true}, {"name": "baseUrl", "value": "https://httpbin.org", "source": "http-client.env.json [dev]"} ], "captures": ["email = body.$.email"], "asserts": ["status == 200", "body.$.authenticated == true"], "refs": ["login"], "auth": "bearer {{token}}", "auth_source": "apic.yaml", "ready": true } ``` `auth` and `auth_source` are present when a `# @auth` directive or `auth.default` applies; see [auth.md](https://apic.sh/auth/). `proxy` is present when a proxy is configured by flag, `apic.yaml` or the environment: `{"url": "http://***@proxy.internal:3128", "source": "apic.yaml"}`, or `{"off": true, "source": "noProxy"}` for a host that bypasses it (the source is `--no-proxy`, `--proxy`, `apic.yaml`, the environment variable's name, or `noProxy`). The same object appears as `request.proxy` in `run --json` and as `proxy` in `env --json`, and `run -v` prints it under the request headers. `refs` lists the request's `# @ref` and `# @forceRef` targets, and a missing variable has `"ref_runs": true` when one of them captures it, so `ready` stays true. Sources are one of `--var`, `shell APIC_VAR_<name>`, `captured this run`, `session`, `http-client.private.env.json [env]`, `http-client.env.json [env]`, `.env`, `<file>:<line> @<name>`, `built-in`, `response reference (flow only)` or `missing`. Values with `"secret": true` (`--var`, `APIC_VAR_`, values captured this run, the session, the private env file and `.env`) are shown as `***`. ## apic env ``` apic env ``` Environments found, which env files exist, the current environment, every variable in effect with its source, and the JetBrains [`Security.Auth`](https://apic.sh/auth/#jetbrains-projects) configurations with the oauth2 spec each maps to. Secrets are masked. `--json`: ```json { "root": "/abs/path/api", "environments": ["dev", "staging"], "current": "dev", "files": ["http-client.env.json", "http-client.private.env.json", ".env"], "variables": [ {"name": "baseUrl", "value": "https://dev.example.com", "source": "http-client.env.json [dev]"}, {"name": "password", "value": "***", "source": "http-client.private.env.json [dev]", "secret": true} ], "auth": [ {"name": "my-api", "spec": "oauth2 clientId={{clientId}} clientSecret=*** grant=client_credentials tokenUrl=https://login.example.com/oauth2/token", "files": ["http-client.env.json", "http-client.private.env.json"]} ] } ``` `auth` is omitted when the env files declare no configurations. An entry apic cannot use has `error` instead of `spec`; `ignored` lists fields it does not act on. ## apic session ``` apic session apic session clear [--all] ``` `session` prints captured values per environment from `.apic/session.json` (in clear text, since this is the one place you may need to see them). Tokens cached by `# @auth oauth2` and `# @auth exec ttl=` appear as `$oauth2:<hash>` and `$exec:<hash>` entries with their remaining lifetime. Cookies kept by the [cookie jar](https://apic.sh/format/#cookies) are listed under the same environment with their name, scope and expiry, values masked. `clear` forgets the current environment's values and cookies, or every environment's with `--all`. `--json` on `session` prints the raw map `{"<env>": {"<name>": "<value>"}}`; cookies are not in it. `session cookies` lists the jar on its own, and with `--json` prints `{"<env>": [{"name", "domain", "path", "expires", "secure", "http_only"}]}`, never the values. ## apic history ``` apic history [request] [--show N] [-v] apic history diff <request> [from] [to] apic history clear <request> | --all [--every-env] ``` Response history is off until `apic.yaml` sets `history: N` (`apic init` and `apic demo` write `history: 10`). Then every `apic run`, the UI and MCP's `run_request` and `run_file` keep the last `N` responses of each named request, per environment, in `.apic/history/<env>/<request>/`. Unnamed requests, `--no-session` runs, `apic run --data` and `apic test` record nothing. A request that `# @ref` ran first gets its own entry. A name two files both use is kept apart as `file.http#name`, the target that picks either one. Each entry is the result as `apic run --json` prints it, `saved_to` from `--output` included, so sensitive headers are masked and a `--redact` run stores the redacted form. A history that cannot be written (a read-only checkout, a full disk) does not fail the run: the result carries a `warnings` entry instead. See [Security](https://github.com/hungovercoders/apic/blob/main/SECURITY.md) for what that leaves on disk. `history <request>` lists the entries newest first, numbered from 1, with the time, status, duration and size. With no request it lists the requests that have history in the environment. `--show N` prints entry N as `apic run` printed it (`-v` adds the headers). A request that has since been renamed or deleted keeps its history and can still be read and cleared by its old name. A request named `diff` or `clear` is reached as `apic history file.http#diff`, since the bare word is the subcommand. `history diff` compares two entries, by default `2` (the one before) with `1` (the latest): first the status, then the body. A JSON body is compared by structure, with keys in sorted order and arrays index by index, and each change is a JSONPath of the kind `# @assert` reads. A text body is compared line by line. Headers are left out, since a `Date` or a request id differs every time: ```text $ apic history diff list-todos list-todos #2 (2026-10-06 10:00:01, 200) → #1 (2026-10-06 10:05:03, 200) ~ $[0].done: false → true + $[2]: {"done":false,"id":"3","title":"Write docs"} 2 changes ``` `history clear <request>` forgets one request's history in the current environment, `history clear --all` every request's in the environment, and `--every-env` every request's in every environment. A bare `history clear` is refused rather than taken to mean the whole environment. With `--json`: | Command | Prints | |---|---| | `history` | `{"env", "keep", "requests": [{"request", "entries"}]}` | | `history <request>` | `{"env", "request", "keep", "entries": [{"index", "time", "ok", "status", "status_text", "duration_ms", "size", "file"}]}` | | `history <request> --show N` | the entry's fields and `"result"`, the stored `apic run --json` object | | `history diff` | `{"env", "request", "from", "to", "changes": [{"path", "op", "from", "to"}]}`; `op` is `added`, `removed` or `changed`, and `from` and `to` are JSON values | | `history clear` | `{"cleared": "<env>" or "*", "request", "entries"}` | ## apic select ``` apic select <request> <selector> [--entry N] ``` Evaluates a selector, the kind `# @assert` and `# @capture` take, against the newest response recorded for the request in the current environment (or entry `N` with `--entry`, 1 being the newest) and prints the value: `body.$.items[0].id`, `body.$.items.#`, `header.etag`, `status`. An object or array is pretty-printed. Nothing is sent. It is for looking at a response again, or at the rest of a body that `apic run --body-limit` cut, without repeating a call that may have changed something, which is what an agent otherwise does. It reads the [response history](#apic-history), so `apic.yaml` needs `history: N`; with history off and nothing recorded the error says so. An entry keeps one value per header, joined with commas as `apic run --json` prints them, so `header.<name>.#` and `header.<name>[n]` are refused; sensitive response headers are stored masked, so `header.set-cookie` and `cookie.<name>` read as `***`, and an entry a `--redact` run recorded is refused outright, its body being masked too. Nothing at the selector exits 1, like a capture that finds nothing; a selector apic does not know, an entry past the history, or a redacted entry is E203. `--json` prints `{"request", "env", "entry", "time", "selector", "found", "value"}`, the value as JSON (a number, boolean, null, array or object as itself, text as a string). ## apic curl ``` apic curl <target> ``` Prints a POSIX-shell `curl` command with every variable resolved, one flag per line. Auth is mapped onto curl's `--user` and `--aws-sigv4` flags where possible (see [auth.md](https://apic.sh/auth/)). Fails with exit code 2 and the usual hint if a variable is missing. Useful for a machine without apic, for a bug report, or for pasting into a Taskfile. ```sh apic curl create-user --env staging apic curl get-user | sh ``` `--json` wraps it as `{"id": "get-user", "command": "curl -sS ..."}`. With `--redact` the command is safe to paste into a stored log but no longer runnable as printed: header values, the body and query-string values are masked, and `bearer`/`basic` credentials become `$TOKEN` and `$APIC_USER`/`$APIC_PASSWORD` — the same shell placeholders the `aws`, `oauth2` and `exec` exports already use. Without it, the command runs as printed, credentials included. `apic curl` is [`apic snippet --lang curl`](#apic-snippet), kept for its own `--json` shape. ## apic snippet ``` apic snippet <target> [--lang curl|httpie|powershell|python|js|go] ``` The request as code in another language, every variable resolved, for a machine without apic, a service's README or a colleague on Windows: | `--lang` | What it prints | |---|---| | `curl` (default) | The `apic curl` command | | `httpie` | An [HTTPie](https://httpie.io/cli) command, `http --ignore-stdin …` | | `powershell` | `Invoke-RestMethod` for PowerShell 7, with `-Headers`, `-Body` or `-Form`, `-HttpVersion`, `-SkipCertificateCheck` and `-Proxy` where they apply | | `python` | A script using [requests](https://requests.readthedocs.io/): `requests.request(...)` with `headers`, `params`, `auth`, `data`/`files`, `verify`, `cert` and `proxies` | | `js` | `fetch` for Node 18+ (an ES module) or a browser, with `FormData` for a multipart body | | `go` | A `package main` program using `net/http`, formatted by gofmt | Auth follows the [curl export](https://apic.sh/auth/#curl-export): bearer, basic, apikey and digest become what each language uses for them. The rules for secrets are curl's too: without `--redact` the snippet runs as printed, credentials included; with it the values are masked and the credentials come from the environment (`TOKEN`, `APIC_USER`, `APIC_PASSWORD`, `APIC_API_KEY`, read as `$env:TOKEN`, `os.environ["TOKEN"]`, `process.env.TOKEN`, `os.Getenv("TOKEN")`). What a language cannot do on its own is said in a comment at the top: AWS SigV4 signing, digest auth in `fetch` and Go, a CA file or client certificate where the snippet cannot point at one, a proxy for `fetch`, a required HTTP/2. A missing variable fails with exit code 2, as for `apic curl`. ```sh apic snippet get-user --lang python apic snippet create-order --lang powershell --redact apic snippet login --lang go > login.go ``` `--json` wraps it as `{"id": "get-user", "lang": "python", "code": "..."}`. In [the UI](https://apic.sh/tui/), <kbd>c</kbd> shows the selected request as curl and each press moves to the next language. ## apic fmt ``` apic fmt [path|file.http#name...] [--check] [--diff] apic fmt - < file.http ``` Rewrites request files in their canonical form, so files written by several people (or agents) stop drifting: - one blank line between blocks, `### Title` on its own line; - directives in a fixed order: `name`, `description`, `disabled`, `step`, `auth`, `ref`, `forceRef`, `sleep`, `retry`, `timeout`, `no-redirect`, `no-session`, `no-cookies`, `assert`, `capture`, then unknown ones as written; comments keep their place among them; - `@name = value` file variables, the request line and header names (`Content-Type`) with single spaces and canonical case, query continuations indented four spaces; - a JSON body pretty-printed with two spaces when it parses and holds no `{{placeholders}}`; every other body, file bodies and editor script blocks kept byte for byte, only the blank lines around them dropped; - comments travel with the directive below them when directives are reordered; - trailing whitespace removed outside bodies, one final newline. Formatting twice changes nothing. Without paths every request file of the project is formatted; a path may be a file or a directory. `file.http#name` (or `file.http#3`, counting requests as `apic run file.http#3` does) formats that one request and leaves the rest of the file byte for byte, so an agent that added a request to a file it does not own can format its own change and nothing else; a name that is not in the file is E201. `-` reads stdin and writes the result to stdout, which is what the VS Code extension's **Format Document** uses. | Flag | Meaning | |---|---| | `--check` | Write nothing; list the files that would change and exit 1 if there are any (a CI gate). | | `--diff` | Write nothing; print a unified diff of what would change and exit 1 if there is any. | `--json` prints only `{"files": N, "changed": [...], "formatted": bool}` (plus `"diff": {file: text}` under `--diff`); nothing else goes to stdout, so the output stays one parseable object. ## apic validate ``` apic validate [--format text|json|github|sarif] ``` Parses every `.http` file and reports errors (bad directive syntax, header lines that are not headers, unknown selectors, missing body files, unparsable assertions) and warnings (unknown `# @` directives, duplicate request names). Exit code 2 when there are errors. Meant for CI and pre-commit. Every diagnostic points at the offending text, not just its line, and carries a stable code: ``` users.http:12:11: error: assert "bogus == 1": unknown selector "bogus" (unknown-selector) # @assert bogus == 1 ^^^^^ ``` The source line and caret appear when stdout is a terminal. | Flag | Meaning | |---|---| | `-f, --format text` | The default above. | | `-f, --format json` | Same as `--json`. | | `-f, --format github` | GitHub Actions workflow commands (`::error file=…,line=…,col=…::…`), so a `validate` step annotates the pull request at the right place. | | `-f, --format sarif` | SARIF 2.1.0, with one rule per code, for `github/codeql-action/upload-sarif` or any SARIF viewer. | `--json`: ```json { "ok": false, "files": 2, "requests": 5, "diagnostics": [ {"path": "users.http", "line": 12, "column": 11, "end_line": 12, "end_column": 16, "severity": "error", "code": "unknown-selector", "message": "assert \"bogus == 1\": unknown selector \"bogus\""} ] } ``` `line` and `column` are 1-based; `column` counts bytes from the start of the line, and `end_column` is exclusive. The span fields and `code` are omitted when a diagnostic has no useful span (a problem in `apic.yaml`). They were added in 0.2; the earlier keys are unchanged. Codes: | Code | Meaning | |---|---| | `orphan-directives` | Directives that are not followed by a request line. | | `bad-name` | `# @name` without a value. | | `bad-capture` | `# @capture` that is not `name = selector`. | | `bad-assert` | `# @assert` that is not `selector op value`. | | `bad-header` | A line in the header section that is not `Name: value`. | | `unknown-directive` | A `# @directive` apic does not know; ignored (warning). | | `editor-script` | An editor-only script or redirect block; skipped, not sent (warning). | | `duplicate-name` | A request name used more than once in the project (warning). | | `bad-auth` | An `# @auth` spec that does not parse. | | `exec-disabled` | `# @auth exec` without `auth.allowExec` in `apic.yaml` (warning). | | `bad-config-auth` | `auth.default` in `apic.yaml` does not parse. | | `bad-step` | A `# @step` phrase that does not parse. | | `ambiguous-step` | A `# @step` phrase that matches the same text as another step. | | `bad-ref` | A `# @ref` or `# @forceRef` whose target is not exactly one request in the project. | | `ref-cycle` | A `# @ref` chain that leads back to the request it started from. | | `bad-retry` | A `# @retry` directive, or `retry` in `apic.yaml`, that is not `<attempts> [interval]`. | | `bad-sleep` | A `# @sleep` whose value is not a duration such as `500ms` or `2s`. | | `bad-http-version` | A request line whose HTTP version is not `HTTP/1.1` or `HTTP/2`. | | `bad-auth-config` | A JetBrains `Security.Auth` configuration apic cannot use: not OAuth2, the Implicit grant, a missing Token URL or Client ID. | | `unknown-auth-key` | A warning: a `Security.Auth` field apic does not act on. | | `unknown-selector` | A selector that is not `status`, `statusText`, `duration`, `header.*`, `body` or `body.$*`. | | `missing-body-file` | A `< file` body, or a `< file` part of a multipart body, whose file does not exist. | | `bad-multipart` | A `multipart/form-data` body without a boundary, or whose parts are not laid out between `--boundary` delimiters. | | `bad-graphql` | A GraphQL request (`GRAPHQL` method or `X-REQUEST-TYPE: GraphQL`) without a query, or whose variables block is not a JSON object. | | `bad-save-path` | A `>> file` line with no path, a path outside the project, or a second one on the same request. | | `missing-schema-file` | A `# @assert … matchesSchema <file>` whose schema file does not exist or lies outside the project. | In a GitHub Actions workflow: ```yaml - run: apic validate -C api --format github ``` ## apic import ``` apic import <openapi.yaml|openapi.json> [-o <dir>] [--env-name <name>] [--force] apic import <collection.postman.json> [-o <dir>] [--postman-env <file>]... [--force] apic import --curl '<command>' [--into <file.http>] [--name <name>] ``` The format is detected from the file. From an OpenAPI 3 document it scaffolds `.http` files: - one file per tag (`pets.http`), operations without tags go to `api.http`; - one request per operation named from `operationId` in kebab-case, else from method and path; - `# @assert status == <first 2xx code>` (a `2XX` key becomes a range check; an operation that declares no 2xx response gets no status assertion); - path parameters as `{{param}}`; required query and header parameters as `{{vars}}`, optional ones as commented lines; - a JSON body built from the request schema, using examples, defaults and enums when present, `{{$uuid}}` and `{{$isoTimestamp}}` for uuid and date-time strings; - `http-client.env.json` with `baseUrl` from the first non-empty server, with server variables replaced by their defaults. Accepts OpenAPI 3.0 and 3.1 in YAML or JSON. Local `$ref` pointers (`#/components/...`) are resolved for parameters, request bodies and schemas; references to other files are not. Path-level parameters are merged into each operation. Swagger 2.0 documents are rejected with a message. Existing files are kept unless `--force` is given. From a Postman collection (v2.1, or v2.0 where the shapes coincide; v1 exports are refused with a message): - folders become files (`todos.http`; nested folders join with `-`, `todos-archive.http`), requests outside any folder go to a file named after the collection; - each request becomes a named request (kebab-case of its name, de-duplicated with a numeric suffix) with its description; - URL, method, headers and query map as written: Postman's `{{var}}` is apic's, `:id` path variables become `{{id}}` with their value as a file variable, `{{$guid}}` becomes `{{$uuid}}`, disabled headers and query parameters become comments; - bodies: raw (with a `Content-Type` from the language when no header sets one), urlencoded, form-data (as a [multipart body](https://apic.sh/format/#multipart-uploads), file parts pointing at a file of the same name beside the `.http` file), a whole-body file, and GraphQL as a JSON `{"query", "variables"}` POST; - auth: bearer, basic, digest, awsv4 and oauth2 (client credentials and password grants) become `# @auth`; an API key becomes the header or query value; the collection's own auth becomes `auth.default` in `apic.yaml`; a request with "no auth" under it gets `# @auth none`; NTLM, Hawk and the browser OAuth2 flows are reported; - variables: the collection's become `$shared` in `http-client.env.json`, and each `--postman-env` file becomes an environment named after it, its `secret` values going to `http-client.private.env.json` (written `0600`); the first environment becomes `env:` in `apic.yaml`; - `pm.test` scripts: `pm.response.to.have.status(200)`, `pm.expect(jsonData.x).to.eql(...)` (also `include`, `exist`, `be.true`), header equality and `include`, `pm.response.to.have.header(...)`, `responseTime` bounds and `pm.expect(pm.response.text()).to.include(...)` become `# @assert`; `pm.environment.set("token", jsonData.token)` (and the `collectionVariables`, `globals` and header forms) become `# @capture`. Every other line, pre-request scripts included, is listed under `unsupported` with the request and a reason, and printed as a `note` line. From a curl command (`--curl`, the reverse of `apic curl`): one `###` block with `# @name` (from `--name`, else the method and path, so `POST /todos` becomes `post-todos`), `# @assert status == 200`, the headers, and the body. It reads `-X`, `-H`, `-d`/`--data`/`--data-raw`/ `--data-binary`/`--data-urlencode` (`@file` becomes `< ./file`), `-F` and `--form-string` (a multipart body), `-u` (`# @auth basic`), `--url`, `-G`, `-I`, `-b` (a `Cookie` header), `-A`, `-e`, `-k` (a comment: run with `--insecure`), `-L` and `--compressed`, in both quote styles, with `$'…'` escapes and backslash line continuations. Flags about curl's own output or transport are ignored with a note; an unknown flag is a note, not an error. When the project's environment has a `baseUrl` that prefixes the URL, the host becomes `{{baseUrl}}`. Without `--into` the block is printed; with it the block is appended to that file, relative to the project root, created if needed, with a numeric suffix on a name the file already has. `--curl -` reads the command from stdin. | Flag | Meaning | |---|---| | `-o, --out <dir>` | Output directory. Default `.`. | | `--env-name <name>` | Environment name in the generated env file (OpenAPI). Default `dev`. | | `--postman-env <file>` | A Postman environment export to import as an environment. Repeatable. | | `--force` | Overwrite existing files. | | `--curl <command>` | A curl command to turn into a request block; `-` reads stdin. | | `--into <file.http>` | Append the block to this file instead of printing it. | | `--name <name>` | The request's `# @name`. | `--json` prints `{"files": [...], "requests": N, "base_url": "...", "env_file": "...", "skipped": [...]}`; for a collection it adds `private_env_file` and `unsupported: [{"request", "what", "reason"}]`. For `--curl` it prints `{"file", "name", "request", "warnings": [...]}`. ## apic mcp ``` apic mcp [--dir <path>] [--env <name>] [--http <host:port> [--token <bearer>]] apic mcp install [dir] [--to <file>]... ``` Serves the project over the Model Context Protocol on stdin/stdout until the client disconnects. Tools: `list_requests`, `describe_request`, `run_request`, `run_file`, `run_features`, `list_environments`, `clear_session`, `validate_project`, `curl_request`. Each `.http` file is a resource. `--env` sets the default environment for calls that do not pass one. See [agents.md](https://apic.sh/agents/). | Flag | Meaning | |---|---| | `--http <host:port>` | Serve the streamable HTTP transport on this address instead of stdio. | | `--token <bearer>` | The bearer token clients must send. Default `$APIC_MCP_TOKEN`. Required when `--http` binds anything but the loopback interface; the server refuses to start otherwise. | ```sh apic mcp install -C api --env dev # .mcp.json, read by Claude Code claude mcp add api -- apic mcp --dir ./api --env dev # the same, by hand ``` `mcp install` writes the entry into `<dir>/.mcp.json` (`dir` defaults to the current directory), the project-scoped configuration Claude Code reads from the directory it starts in, so every clone of the repository registers the server without a command of its own. The entry runs `apic mcp`, with `--dir` naming the project (`-C`) relative to `dir` when the two differ and `--env` when one is given. Other servers in the file are kept, an entry already named `api` is replaced, and one already holding the same text is reported as `unchanged`; an empty file is an empty document, and a file that is not a JSON object, or whose `mcpServers` is not one, is E210 rather than overwritten. `apic init` writes the same entry into a new project (`--no-mcp` leaves it out), keeping one already there unless `--force`. | Flag | Meaning | |---|---| | `--to <file>` | Write this file under `dir` instead of `.mcp.json`; repeatable. `.cursor/mcp.json` for Cursor, which reads the same shape. | `--json` prints `{"written": [...], "unchanged": [...]}`. For a client that installs servers from a catalogue, apic is listed in the [MCP registry](https://registry.modelcontextprotocol.io/) as `io.github.hungovercoders/apic`, running the `ghcr.io/hungovercoders/apic` image with the project mounted at `/work`. ## apic lsp ``` apic lsp [--dir <path>] [--env <name>] ``` A Language Server Protocol server on stdin/stdout, for Neovim, Helix, JetBrains IDEs, Emacs or any editor with an LSP client; the set-up for each is in [editors.md](https://apic.sh/editors/#any-editor-with-an-lsp-client). It publishes `apic validate`'s diagnostics for open buffers as they change (and for `apic.yaml` and the env files when they change on disk), completes directives, variables, selectors, operators, auth types and `# @ref` targets, shows a variable's value and source on hover with secrets masked, formats with `apic fmt`, and offers Run, Describe and curl code lenses that it executes itself (`apic.lsp.run`, `apic.lsp.describe`, `apic.lsp.curl` through `workspace/executeCommand`, answering with what `run --json`, `describe --json` and `curl --redact` print; the curl command lands in a notification and the editor's log, so its credentials are shell placeholders). The project root is found per file: inside a workspace folder, the nearest directory holding `apic.yaml` or an `http-client` env file, without leaving the folder, else the folder itself; outside every folder, the file's own directory. `--dir` stands in for a client that names no workspace. A project nested in another keeps its own diagnostics, so two projects that each have a `login` are no clash. An edit is checked once typing pauses (150 ms); a completion, hover or lens for the file checks it first. The initialisation options: | Option | Meaning | |---|---| | `env` | The environment for hover, completion and runs; else `--env`, else `apic.yaml`'s `env:`. | | `envs` | The environment per project root, `{"/path/to/api": "staging"}`, for a client that picks one per project. | | `projectRoots` | Fixes the project root of every file in a workspace folder, `{"/path/to/folder": "/path/to/folder/api"}`, as the VS Code extension's `apic.projectDir` does. | | `codeLens`, `formatting` | `false` leaves that feature to a client with its own, as the VS Code extension does. | `workspace/didChangeConfiguration` with `{"apic": {"env": "staging"}}` or `{"apic": {"envs": {"/path/to/api": "staging"}}}` changes them (an empty value goes back to the default). The workspace is checked when the client is ready, so problems in files that are not open show too, and `apic.lsp.validate` (no arguments) checks it again and answers once the diagnostics are out. A run through a code lens writes the session and the [response history](#apic-history) as `apic run` does. The server speaks JSON-RPC on stdout, so `--json` changes nothing for it. It exits 0 after a `shutdown` request and an `exit` notification, and 1 when the client exits or closes the stream without one, as the protocol asks. ## apic demo ``` apic demo [--out <dir>] [--port <port>] [--force] ``` Writes a local example project (`apic.yaml`, `http-client.env.json`, `http-client.private.env.json`, `auth.http`, `explore.http`, `jobs.http`, `todos.http` and `features/todos.feature`) into `--out`, then starts the bundled fake API and serves until you stop the process. The API has login, basic, OAuth2 client-credentials and API-key routes, a todos resource with filtering, pagination and validation errors, jobs that finish after two polls, a multipart upload, a GraphQL endpoint, a CSV report, a slow route and a health check; `apic list -C apic-demo` shows the requests that use them. | Flag | Meaning | |---|---| | `-o, --out <dir>` | Output directory for the scaffolded example project. Default `apic-demo`. | | `--port <port>` | Localhost port to serve on and to write into `http-client.env.json`. Must be `1-65535`. Default `8089`. | | `--force` | Overwrite existing scaffold files in `--out`. | `--json` prints one startup object and then keeps serving: ```json { "out": "apic-demo", "url": "http://localhost:8089", "written": ["apic-demo/apic.yaml"], "listening": true } ``` `skipped` lists the files that were already there and were left alone; it is omitted when there are none. ## apic mock ``` apic mock <openapi.yaml|openapi.json> [--port <port>] ``` Serves an OpenAPI 3 document as a mock API, so the requests [`apic import`](#apic-import) wrote from the same document can run before the API exists. Every operation answers with the response the document declares: - the first 2xx response, else `default`, else the first one declared; a `2XX` key serves 200, and an operation with no responses answers 200 with no body; - a body from the media type's `example`, its first named `examples` entry, else a value built from the schema the way `import` builds request bodies (examples, defaults and enums when present, fixed sample values for `uuid` and `date-time` strings, so the same call gives the same answer every time); - the response's declared `headers`, from their examples or schemas, and `Content-Type` from the media type; an `Accept` header picks among the media types, the first is served otherwise. A `Prefer` header line on a request picks another documented response for that request: `Prefer: code=404` serves the `404` response (its class, `4XX`, or `default` served with that status when the exact code is not declared), and `Prefer: example=name` one of the media type's named examples. A choice the document does not offer is a 406 whose JSON body says what is missing. An unknown path is a 404 and a known path under another method a 405 with `Allow`, both with a JSON body, so `apic run` shows why. Paths are served as written and, when the first server URL has a path such as `/v1`, under that prefix too, so `baseUrl` can be either. The server listens on localhost only. It keeps no state and validates nothing: a `POST` answers with the document's example, not with what was sent, and a later `GET` does not know about it. For a stateful fake with a known shape there is [`apic demo`](#apic-demo); the [comparison](https://apic.sh/comparison/#deliberately-not-planned) page says what the mock will not grow into. | Flag | Meaning | |---|---| | `--port <port>` | Localhost port to serve on. Must be `1-65535`. Default `8090`. | ```sh apic mock openapi.yaml # terminal 1 apic import openapi.yaml -o api # terminal 2: the requests it describes apic run list-pets -C api --var baseUrl=http://localhost:8090 ``` `--json` prints one startup object and then keeps serving: ```json { "spec": "openapi.yaml", "url": "http://localhost:8090", "routes": [ {"method": "GET", "path": "/pets", "status": 200, "name": "listPets"}, {"method": "GET", "path": "/pets/{petId}", "status": 200, "name": "showPetById"} ], "listening": true } ``` `skipped` lists operations that could not be served, with the reason (two path templates that cannot be told apart, such as `/a/{x}` and `/{y}/b`); it is omitted when there are none. A document that is not OpenAPI 3, has a `$ref` that does not resolve or declares no operations is `E215`. ## apic init ``` apic init [dir] [--base-url URL] [--env NAME] [--force] [--no-skill] [--no-mcp] ``` Writes a working starting point into `dir` (default: the current directory): `apic.yaml` (with `history: 10`, so `apic history` and `apic select` work from the first run), `http-client.env.json`, a `http-client.private.env.json` with mode 0600, `api.http` with two annotated requests, a `features/smoke.feature`, `.gitignore` lines for the private env file, `.env` and `.apic/`, the [Agent Skill](https://apic.sh/agents/#3-a-skill-claude-code-codex-cursor-any-agent-that-loads-skills) under `.claude/skills/apic` and `.agents/skills/apic`, so an AI agent working in the project knows how to use apic from the first session (`apic skill install --all` adds the `api-design` and `api-security` skills, which are opinions about the API itself and so an opt-in), and a `.mcp.json` registering [`apic mcp`](#apic-mcp) for the agents that read it. Existing files are kept unless `--force` is given, the skill's and an `apic mcp` entry already in `.mcp.json` included (`apic skill install` and `apic mcp install` refresh them); the `.gitignore` is appended to and the rest of `.mcp.json` kept. | Flag | Default | Meaning | |---|---|---| | `--base-url` | `https://api.example.com` | `baseUrl` for the environment. | | `--env` | `dev` | Name of the first environment, also written as `env:` in `apic.yaml`. | | `--force` | off | Overwrite files that already exist. | | `--no-skill` | off | Do not write the Agent Skill. | | `--no-mcp` | off | Do not register `apic mcp` in `.mcp.json`. | `--json` prints `{"out", "env", "written", "skipped"}`. ## apic skill ``` apic skill [name] apic skill install [dir] [--all | --skill <name>...] [--to <dir>]... apic skill install --user [--all | --skill <name>...] ``` `skill` prints a skill's `SKILL.md`, the briefing an AI agent reads before working on a project. The binary carries a pack of three, each a directory under [`skills/`](https://github.com/hungovercoders/apic/tree/main/skills) in the repository, compiled in so an agent that can run commands gets the whole briefing with no repository or network: | Skill | What it briefs the agent on | |---|---| | `apic` (the default) | Using apic: the validate, list, describe, run workflow, the `--json` shape and exit codes, the error codes to branch on, how to write a request and where secrets belong; `references/cheatsheet.md` is the [cheat sheet](https://apic.sh/cheatsheet/) | | `api-design` | Designing the HTTP API those requests call: resources and URLs, methods and status codes, problem-details errors, pagination, versioning, idempotency, caching, long-running work and the OpenAPI document, each decision proved by a request `apic run` sends or a mock `apic mock` serves; `references/http-semantics.md` and `references/openapi.md` hold the tables, a contract skeleton and the review checklist | | `api-security` | Keeping that API safe and showing it: the OWASP API Security Top 10 as checks, authentication, authorisation, input and resource limits, headers and CORS, secrets and logging, each a request or Gherkin scenario that fails while the control is missing; `references/owasp-api-top-10.md` and `references/checks.md` hold the expansions, a bank of ready checks and the release checklist | `apic skill api-design` prints that one. `--json` prints `{"name", "files": {"SKILL.md": …, "references/…": …}, "skills": ["apic", "api-design", "api-security"]}` for the skill named (or `apic`). A name that is not in the pack is `E203`, listing the names that are. `skill install` writes the `apic` skill into `<dir>/.claude/skills/apic` (what Claude Code reads) and `<dir>/.agents/skills/apic` (what Codex, Cursor and the other agents that share that directory read), `dir` being the project (`-C`) unless given; it must exist, so a mistyped directory is E210 rather than a new tree. The `apic` skill is about using apic, so it is the default; `api-design` and `api-security` are opinions about the reader's own API, so a project opts into them with `--all` (the whole pack) or `--skill <name>` (exactly the skills named; a name given twice counts once). A file already holding the same text is reported as `unchanged`; any other is overwritten, since the text is apic's rather than the project's. Commit the result so every clone briefs its agents. `apic init` writes the `apic` skill the same way, keeping existing files unless `--force`. `skill install --user` writes the same directories under your home directory (`~/.claude/skills/<name>` and `~/.agents/skills/<name>`), where Claude Code and the other agents read skills for every project, so one install after installing apic briefs them everywhere. It takes no `dir`, `-C` or `--to` (E203), since those name a project; a `~/.claude` or `~/.agents` that a dotfile manager links elsewhere is followed. `--all` and `--skill` choose the skills as above, and a second run reports every file `unchanged`. | Flag | Meaning | |---|---| | `--all` | Install the whole pack, `apic`, `api-design` and `api-security`, instead of `apic` alone. | | `--skill <name>` | Install exactly this skill; repeatable. Not with `--all`. | | `--to <dir>` | Install into this directory under the project instead of the two defaults; repeatable. `--to .claude/skills` is Claude Code only. | | `--user` | Install under your home directory, for every project, instead of the project. | `--json` prints `{"written": [...], "unchanged": [...]}`. ## apic version, apic completion `version` prints the version, commit, Go version and platform. With `--json`: ```json {"version": "v1.2.3", "commit": "abc1234", "date": "2026-02-01T10:00:00Z", "go": "go1.26.11", "os": "linux", "arch": "amd64"} ``` `completion bash|zsh|fish|powershell` prints a shell completion script: ```sh source <(apic completion bash) apic completion zsh > "${fpath[1]}/_apic" ``` Completion knows the project: `run`, `describe`, `curl`, `snippet`, `select` and `history` complete request ids and `.http` file names, and `--env` completes the environments in `http-client.env.json`. ## Configuration file `apic.yaml` in the project root, all keys optional: ```yaml # yaml-language-server: $schema=https://apic.sh/schemas/apic.schema.json env: dev # default --env dir: requests # subdirectory to scan for .http files timeout: 30s # default request timeout retry: 10 2s # default retry policy for requests without # @retry; see format.md maxBodyBytes: 67108864 # cap on the response body read into memory (default 64 MiB) cookies: true # keep a cookie jar per environment in .apic/cookies.json (default off) history: 20 # keep the last 20 responses of each request in .apic/history (default off) proxy: http://proxy.internal:3128 # every request goes through it; --proxy beats it, --no-proxy skips it noProxy: [localhost, .internal] # hosts that bypass proxy: name, host:port, .suffix, IP, CIDR or * tls: # a private CA and a client certificate; see auth.md caFile: certs/internal-ca.pem certFile: certs/client.pem keyFile: certs/client-key.pem hosts: api.internal.example.com: {certFile: certs/internal.pem, keyFile: certs/internal-key.pem} auth: default: aws region=eu-west-2 # applied to requests without # @auth; see auth.md allowExec: false # permit # @auth exec test: paths: [features, smoke.feature] # what `apic test` runs by default ``` The first line is optional. It points the YAML language server (VS Code with the YAML extension, JetBrains, Neovim) at the published schema, which gives completion, descriptions and validation for every key; `apic init` writes it for you. The schemas are generated from apic's own types, so they cannot drift from what the binary reads: | File | Schema | |---|---| | `apic.yaml` | [`schemas/apic.schema.json`](schemas/apic.schema.json) | | `http-client.env.json`, `http-client.private.env.json` | [`schemas/http-client.env.schema.json`](schemas/http-client.env.schema.json) | | `.apic/session.json` | [`schemas/session.schema.json`](schemas/session.schema.json) | For the JSON files, add `"$schema"` is not part of the format the other `.http` tools read, so associate the schema in the editor instead: in VS Code, `json.schemas` in settings with `fileMatch: ["http-client*.env.json"]` and the URL above. ## Files apic reads and writes | File | Purpose | |---|---| | `*.http`, `*.rest` | Request definitions. | | `*.feature` | Gherkin specs for `apic test`. | | `apic.yaml` | Defaults. | | `http-client.env.json` | Public per-environment variables. | | `http-client.private.env.json` | Secret per-environment variables. Gitignore it. | | `.env` | `KEY=value` lines; second-lowest precedence, above file `@vars`. | | `.apic/session.json` | Captured values per environment. Written by `run`, cleared by `session clear`. `.apic/.gitignore` is created alongside so it is never committed. | | `.apic/cookies.json` | The cookie jar per environment, when cookies are on. Written `0600` by `run`, cleared by `session clear`, listed by `session cookies`. | | `.apic/history/` | The last responses of each named request per environment, when `history:` is set. One `0600` file per response, written by `run`, read by `history`, cleared by `history clear`. | | `>> file` targets | Response bodies a request saves (`>> ./out.json`, `>>! ./out.json`) or `run --output` writes. Inside the project for `>>`; `0600` when a secret went into the request. | <!-- BEGIN GENERATED: go run ./scripts/clidocs (task docs:cli) rewrites this section; edit the flags in internal/cli instead --> ## Commands and flags Generated from apic's own command tree, so it lists exactly what the binary accepts. The sections above explain each command; this is every flag in one place. `man apic` and `man apic-run` show the same, where the release archive's `man/` pages are installed. ### Global flags These work with every command. | Flag | Meaning | |---|---| | `--cacert <string>` | PEM file with certificates to trust in addition to the system roots | | `--cert <string>` | PEM client certificate to present (mTLS) | | `--cookies` | keep a cookie jar per environment in .apic/cookies.json (or set cookies: true in apic.yaml) | | `-C, --dir <string>` | project root holding .http files and env files (default `.`) | | `-e, --env <string>` | environment from http-client.env.json (default from apic.yaml) | | `--insecure` | skip TLS certificate verification | | `--json` | machine-readable JSON output | | `--key <string>` | PEM private key for --cert (default: the --cert file) | | `--no-color` | disable colour (also honours NO_COLOR) | | `--no-proxy` | send requests directly, ignoring --proxy, apic.yaml and the environment | | `--no-session` | do not read or write captured values in .apic/session.json | | `--proxy <string>` | send requests through this proxy (http, https or socks5 URL); beats proxy: in apic.yaml and HTTP(S)_PROXY | | `--redact` | mask all request headers, bodies, query values and captures in output (for CI logs) | | `--timeout <duration>` | request timeout (default 30s or apic.yaml) | | `--var <string>` | override a variable, name=value (repeatable) | ### apic completion Generate the autocompletion script for the specified shell. ``` apic completion ``` No flags of its own. ### apic completion bash Generate the autocompletion script for bash. ``` apic completion bash ``` | Flag | Meaning | |---|---| | `--no-descriptions` | disable completion descriptions | ### apic completion fish Generate the autocompletion script for fish. ``` apic completion fish [flags] ``` | Flag | Meaning | |---|---| | `--no-descriptions` | disable completion descriptions | ### apic completion powershell Generate the autocompletion script for powershell. ``` apic completion powershell [flags] ``` | Flag | Meaning | |---|---| | `--no-descriptions` | disable completion descriptions | ### apic completion zsh Generate the autocompletion script for zsh. ``` apic completion zsh [flags] ``` | Flag | Meaning | |---|---| | `--no-descriptions` | disable completion descriptions | ### apic curl Print the equivalent curl command (with variables resolved). ``` apic curl <request> ``` No flags of its own. ### apic demo Scaffold and serve a fake API, so apic can be tried with no setup. ``` apic demo [flags] ``` | Flag | Meaning | |---|---| | `--force` | overwrite existing files | | `-o, --out <string>` | directory to write the example project into (default `apic-demo`) | | `--port <int>` | port to serve the demo API on (default `8089`) | ### apic describe Show a request's variables, where each comes from, captures and asserts. ``` apic describe <request> ``` No flags of its own. ### apic env Show environments and the variables in effect. ``` apic env ``` No flags of its own. ### apic fmt Rewrite .http files in their canonical form. ``` apic fmt [path...] [flags] ``` | Flag | Meaning | |---|---| | `--check` | do not write; list the files that would change and exit 1 if any | | `--diff` | do not write; print a unified diff of what would change and exit 1 if any | ### apic history List the responses a request returned before (needs history: N in apic.yaml). ``` apic history [request] [flags] ``` | Flag | Meaning | |---|---| | `--show <int>` | print entry N (1 is the newest) as apic run printed it | | `-v, --verbose` | with --show, include the request and response headers | ### apic history clear Forget the history of a request, or of every request with --all. ``` apic history clear [request] [flags] ``` | Flag | Meaning | |---|---| | `--all` | clear every request's history in the environment | | `--every-env` | clear every request's history in every environment (implies --all) | ### apic history diff Show what changed between two responses (default: the last two). ``` apic history diff <request> [from] [to] ``` No flags of its own. ### apic import Scaffold .http files from an OpenAPI 3 document, a Postman collection or a curl command. ``` apic import <openapi.yaml|openapi.json|collection.postman.json> | --curl <command> [flags] ``` | Flag | Meaning | |---|---| | `--curl <string>` | a curl command to turn into a request (- reads stdin) | | `--env-name <string>` | environment name for the generated http-client.env.json (OpenAPI) (default `dev`) | | `--force` | overwrite existing files | | `--into <string>` | append the request to this .http file (relative to the project root), creating it if needed | | `--name <string>` | request name (default: from the method and path) | | `-o, --out <string>` | directory to write .http files into (default `.`) | | `--postman-env <string>` | Postman environment export to turn into an environment (repeatable) | ### apic init Scaffold a new apic project: config, env files and a first request. ``` apic init [dir] [flags] ``` | Flag | Meaning | |---|---| | `--base-url <string>` | baseUrl for the environment (default `https://api.example.com`) | | `--env <string>` | name of the first environment (default `dev`) | | `--force` | overwrite existing files | | `--no-mcp` | do not register apic mcp in .mcp.json | | `--no-skill` | do not write the Agent Skill into .claude/skills and .agents/skills | ### apic list List every request in the project. ``` apic list [pattern] ``` No flags of its own. ### apic lsp Serve diagnostics, completion, hover, code lenses and formatting to an editor over LSP (stdio). ``` apic lsp ``` No flags of its own. ### apic mcp Serve the project's requests to AI agents over MCP (stdio, or HTTP). ``` apic mcp [--http <host:port> [--token <bearer>]] [flags] ``` | Flag | Meaning | |---|---| | `--http <string>` | serve the streamable HTTP transport on this host:port instead of stdio | | `--token <string>` | bearer token clients must send (default $APIC_MCP_TOKEN); required off the loopback interface | ### apic mcp install Register the server in the project's .mcp.json for the agents that read it. ``` apic mcp install [dir] [flags] ``` | Flag | Meaning | |---|---| | `--to <string>` | file under dir to write instead of .mcp.json (repeatable) | ### apic mock Serve an OpenAPI 3 document as a mock API, so requests can run before the backend exists. ``` apic mock <openapi.yaml|openapi.json> [flags] ``` | Flag | Meaning | |---|---| | `--port <int>` | port to serve the mock API on (default `8090`) | ### apic run Send one request, or every request in a file as a flow. ``` apic run <request|file.http|file.http#name>... [flags] ``` | Flag | Meaning | |---|---| | `--assert <string>` | check the response with an expression, as # @assert would, for this run only (repeatable) | | `--body-limit <string>` | show at most this much of each response body, e.g. 4k or 64k; the result says body_truncated and the history keeps it all | | `--body-only` | print only the response body (for piping) | | `--capture <string>` | capture a value, name=selector, as # @capture would, for this run only (repeatable) | | `--data <string>` | run the targets once per row of a CSV file (header row names the variables) or JSON array of objects; - reads stdin | | `--data-share-session` | with --data, let captures from one iteration reach the next and the session file | | `--dry-run` | resolve the targets and print the requests that would be sent, without sending them | | `--keep-going` | in a flow, continue after a failure | | `--no-retry` | send every request once, ignoring # @retry, --retry and apic.yaml | | `--output <string>` | save the response body to this file (one request only; like a ">>! file" line in the request) | | `--report <string>` | also write a self-contained HTML report of the run to this file | | `--retry <string>` | re-send until the assertions pass: "<attempts> [interval]", e.g. "10 2s" (requests with # @retry keep their own) | | `-v, --verbose` | show request and response headers | ### apic select Read a value out of a request's last recorded response, without sending it again. ``` apic select <request> <selector> [flags] ``` | Flag | Meaning | |---|---| | `--entry <int>` | which recorded response, 1 being the newest (default `1`) | ### apic session Show captured values stored for later runs. ``` apic session ``` No flags of its own. ### apic session clear Forget captured values for the current environment (or --all). ``` apic session clear [flags] ``` | Flag | Meaning | |---|---| | `--all` | clear every environment | ### apic session cookies List the cookies stored per environment (values masked). ``` apic session cookies ``` No flags of its own. ### apic skill Print an Agent Skill from the pack that briefs an AI agent on apic and on APIs. ``` apic skill [name] ``` No flags of its own. ### apic skill install Write the apic skill, or the whole pack, into a project or your home directory. ``` apic skill install [dir] [flags] ``` | Flag | Meaning | |---|---| | `--all` | install the whole pack: apic, api-design, api-security | | `--skill <string>` | a skill of the pack to install, instead of the apic skill alone: apic, api-design, api-security (repeatable) | | `--to <string>` | directory under the project to install into, instead of .claude/skills and .agents/skills (repeatable) | | `--user` | install into .claude/skills and .agents/skills of your home directory, for every project, instead of the project's | ### apic snippet Print the request as code: curl, HTTPie, PowerShell, Python, JavaScript or Go. ``` apic snippet <request> [flags] ``` | Flag | Meaning | |---|---| | `-l, --lang <string>` | language: curl, httpie, powershell, python, js, go (default `curl`) | ### apic test Run Gherkin feature files against the project's requests. ``` apic test [path|file.feature]... [flags] ``` | Flag | Meaning | |---|---| | `-f, --format <string>` | report format: pretty, progress, cucumber, junit, html (default `pretty`) | | `-o, --output <string>` | write the report to a file instead of stdout | | `--steps` | print the built-in step vocabulary and declared phrases, then exit | | `--stop-on-failure` | stop after the first failed scenario | | `-t, --tags <string>` | tag expression, e.g. "@smoke && ~@slow" | | `--use-session` | read and write .apic/session.json instead of an isolated session per scenario | ### apic ui Browse and run the project's requests in a terminal UI. ``` apic ui [flags] ``` | Flag | Meaning | |---|---| | `--demo` | serve the built-in demo API in-process and open the UI on its example project | ### apic validate Parse every .http file and report problems (for CI). ``` apic validate [flags] ``` | Flag | Meaning | |---|---| | `-f, --format <string>` | output format: text, json, github or sarif (default `text`) | ### apic version Print the apic version. ``` apic version ``` No flags of its own. <!-- END GENERATED --> --- # Errors URL: https://apic.sh/errors/ The catalogue of error codes apic reports, each with its meaning and what to do next, for scripts and agents that branch on the code. <!-- Generated by scripts/errdocs from internal/runner/errors.go; edit the catalogue there and run task docs:errors. --> Every error apic reports carries a stable code. A script or an agent can branch on the code rather than on the wording of the message, which may improve from release to release; a code never changes meaning, and new ones are only added. The first digit groups them: **E1xx** is the request as written, **E2xx** the command and the project around it, **E3xx** the network. The exit status follows from the code: 2 for E1xx and E2xx, 3 for E3xx (see [exit codes](https://apic.sh/cli/#exit-codes)). A failed assertion is not an error: it exits 1 and is reported in the result. ## Where the code appears Under the message, with the catalogue's hint when the message does not already name an apic command to run (dim on a terminal, plain in a log): ```text error: auth.http:9: missing variable {{token}}: pass --var token=... 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 ``` With `--json`, as one object on **stderr** (stdout keeps only results, so a pipe into `jq` is not disturbed): ```json {"error":{"code":"E101","title":"missing variable","message":"auth.http:9: missing variable\n {{token}}: it is captured by request …","hint":"Pass it with --var name=value, …","exit":2,"url":"https://apic.sh/errors/#e101"}} ``` Over [MCP](https://apic.sh/agents/), a failed tool call carries the same object as its structured content, and its text ends with the code, title and hint. When the error is about a name that matches nothing but is close to one that exists (a request id, the target of a `# @ref` or an environment, with a typo, the wrong case or `_` for `-`), the message asks "did you mean" and the object carries the closest names, best first, under `suggestions`; an agent can retry with the first rather than listing. The key is absent when nothing is close. ```json {"error":{"code":"E201","title":"unknown request","message":"no request named \"get-usr\"; did you mean get-user? (run `apic list` for every id)","hint":"Run apic list …","exit":2,"url":"https://apic.sh/errors/#e201","suggestions":["get-user"]}} ``` ## Summary | Code | Exit | Title | |---|---|---| | [E101](#e101) | 2 | missing variable | | [E102](#e102) | 2 | request cannot be built | | [E103](#e103) | 2 | request file has errors | | [E104](#e104) | 2 | bad directive value | | [E105](#e105) | 2 | authentication failed | | [E106](#e106) | 2 | body file problem | | [E107](#e107) | 2 | @ref problem | | [E200](#e200) | 2 | error | | [E201](#e201) | 2 | unknown request | | [E202](#e202) | 2 | several requests match | | [E203](#e203) | 2 | bad flag or argument | | [E204](#e204) | 2 | unknown environment | | [E205](#e205) | 2 | project configuration problem | | [E206](#e206) | 2 | TLS configuration problem | | [E207](#e207) | 2 | proxy configuration problem | | [E208](#e208) | 2 | session or cookie store problem | | [E209](#e209) | 2 | bad data file | | [E210](#e210) | 2 | cannot read or write a file | | [E211](#e211) | 2 | import failed | | [E212](#e212) | 2 | feature file problem | | [E213](#e213) | 2 | needs a terminal | | [E214](#e214) | 2 | server could not start | | [E215](#e215) | 2 | mock could not be built | | [E300](#e300) | 3 | request failed | | [E301](#e301) | 3 | could not connect | | [E302](#e302) | 3 | timed out | | [E303](#e303) | 3 | TLS handshake failed | | [E304](#e304) | 3 | protocol problem | | [E305](#e305) | 3 | cancelled | ## E1xx: the request <a id="e101"></a> ### E101 missing variable Exit 2. A `{{placeholder}}` in the request has no value from any source: `--var`, the environment's entry in the env files, `.env`, the session, or a request earlier in the same run. The message names each missing variable and, when another request's `# @capture` provides it, that request. A `# @ref` to that request makes it run first by itself; `apic describe <request>` shows where every variable comes from. **What to do:** Pass it with --var name=value, add it to an env file, or run the request that captures it first. <a id="e102"></a> ### E102 request cannot be built Exit 2. The request's text could not be turned into a request: a built-in with bad arguments (`{{$randomInt 5 1}}`), an unknown built-in, a URL that does not parse once its placeholders are filled in, or a GraphQL body whose variables are not a JSON object. **What to do:** Check the placeholder, URL, header or body the message names. <a id="e103"></a> ### E103 request file has errors Exit 2. The `.http` file failed to parse where the request is: a malformed directive, a multipart body without a boundary, a GraphQL request without a query. apic refuses to send from a file with errors rather than guess; `apic validate` lists them all. **What to do:** Run apic validate to see every problem with its line and column. <a id="e104"></a> ### E104 bad directive value Exit 2. A directive is well formed but its value cannot be used: `# @timeout soon`, `# @retry 0`, `# @sleep -1s`, an `# @assert` that does not parse, an HTTP version other than HTTP/1.1 or HTTP/2 on the request line, or `HTTP/2` over plain `http://`. **What to do:** Fix the directive's value; https://apic.sh/format/ lists what each takes. <a id="e105"></a> ### E105 authentication failed Exit 2. The request's auth could not be applied: an `# @auth` spec that does not parse, `# @auth exec` without `auth.allowExec`, an OAuth2 token endpoint that refused the grant, a browser sign-in with no terminal, or a JetBrains `Security.Auth` configuration that does not exist or cannot be used. **What to do:** Check the # @auth spec (or auth.default), its credentials, and the token endpoint. <a id="e106"></a> ### E106 body file problem Exit 2. A file the request reads could not be used: a `< file` body, a multipart part's file, or a schema for `matchesSchema`. Paths are relative to the `.http` file and must resolve (symlinks included) inside the project root, so a request file cannot read something outside it. **What to do:** Check that the file exists, relative to the .http file, and lies inside the project. <a id="e107"></a> ### E107 @ref problem Exit 2. A `# @ref` or `# @forceRef` names no request, several requests, or leads back to the request it started from. `apic validate` reports these as `bad-ref` and `ref-cycle` before anything runs. **What to do:** Point # @ref at exactly one request, and break any cycle. ## E2xx: the command and project <a id="e200"></a> ### E200 error Exit 2. An error without a more specific code. It should be rare: if you meet one, the message is worth an issue so it can get a code of its own. **What to do:** The message says what went wrong; if it is unclear, please open an issue. <a id="e201"></a> ### E201 unknown request Exit 2. The target names no request: no `# @name` of that name, no such `.http` file, or no request at that position in the file. When a known name is close to the one given (a typo, the wrong case, `_` for `-`), the message asks "did you mean" and the `--json` object lists them under `suggestions`, best first; otherwise the message lists what there is: the request ids, the files, or the named requests of the file given. **What to do:** Run apic list to see the request ids, and use name, file.http, file.http#name or file.http#N. <a id="e202"></a> ### E202 several requests match Exit 2. The command works on one request (`describe`, `curl`, `snippet`) and the target names a whole file or a name used in several files. **What to do:** Pick one with file.http#name, or give the command a single request. <a id="e203"></a> ### E203 bad flag or argument Exit 2. A flag has a value the command cannot use, two flags cannot be combined (`--output` with a flow or `--data`, `--use-session` with `--no-session`), an argument is missing or extra, a history entry number names no entry, or the command does not exist. **What to do:** Check the command's flags with apic <command> --help. <a id="e204"></a> ### E204 unknown environment Exit 2. `--env` (or `env:` in `apic.yaml`) names an environment that neither env file declares, or there are no env files at all. The message lists the environments found and, when one is close to the name given, asks "did you mean"; the `--json` object lists those under `suggestions`. `apic env` shows each environment with its files. **What to do:** Use one of the environments the message lists, or add it to http-client.env.json. <a id="e205"></a> ### E205 project configuration problem Exit 2. The project could not be loaded: `apic.yaml` or an env file is not valid YAML/JSON, or a setting in it (a timeout, a retry policy) cannot be read. **What to do:** Fix apic.yaml or the env file the message names; apic validate helps. <a id="e206"></a> ### E206 TLS configuration problem Exit 2. A TLS setting cannot be used: a CA file with no PEM certificates, a certificate or key that does not load, a key that is world-readable or needs a passphrase apic cannot supply, or a path outside the project. **What to do:** Check the CA file, client certificate and key the message names. <a id="e207"></a> ### E207 proxy configuration problem Exit 2. `--proxy`, `proxy:` in `apic.yaml` or `HTTP(S)_PROXY` holds a URL apic cannot use. apic refuses the request rather than send it directly. **What to do:** Give the proxy as an http, https, socks5 or socks5h URL. <a id="e208"></a> ### E208 session or cookie store problem Exit 2. `.apic/session.json`, the cookie jar or the response history in `.apic/history` could not be read or written, or a session command ran with `--no-session`. **What to do:** Check .apic/ is writable, or run with --no-session. <a id="e209"></a> ### E209 bad data file Exit 2. The rows for `apic run --data` could not be read: an empty file, a header column without a name, a row with the wrong number of fields, or JSON that is not an array of objects. **What to do:** Give --data a CSV file with a header row, or a JSON array of objects. <a id="e210"></a> ### E210 cannot read or write a file Exit 2. A file named on the command line (a report, a data file, a file to format, stdin) could not be read or written. **What to do:** Check the path and its permissions. <a id="e211"></a> ### E211 import failed Exit 2. `apic import` could not read what it was given, or refused to overwrite files without `--force`. **What to do:** Check the input is an OpenAPI 3 document, a Postman v2 collection or a curl command. <a id="e212"></a> ### E212 feature file problem Exit 2. `apic test` could not run the features: no `.feature` files, a feature that does not parse, an invalid tag expression, a step table or variable name it cannot use, or a step naming a target that is not a request. **What to do:** Check the feature files, the step text and the tag expression. <a id="e213"></a> ### E213 needs a terminal Exit 2. `apic ui` is interactive: it refuses `--json` and a stdout that is not a terminal. **What to do:** Run apic ui in a terminal; use apic run or apic list --json in scripts. <a id="e214"></a> ### E214 server could not start Exit 2. `apic mcp --http`, `apic demo` or `apic mock` could not listen where it was asked to. **What to do:** Check the address or port is free and allowed. <a id="e215"></a> ### E215 mock could not be built Exit 2. `apic mock` could not use the document it was given: it is not OpenAPI 3, a `$ref` in it does not resolve, or it declares no operations to serve. **What to do:** Check the file is an OpenAPI 3 document with at least one operation under paths. ## E3xx: the network <a id="e300"></a> ### E300 request failed Exit 3. The request could not complete for a reason none of the E3xx codes below describes. **What to do:** The message has the underlying error; check the URL and the network. <a id="e301"></a> ### E301 could not connect Exit 3. The host name did not resolve, the connection was refused or reset, or the network is unreachable. Nothing reached the server. **What to do:** Check the host name, the port and that the server is running. <a id="e302"></a> ### E302 timed out Exit 3. The server did not answer within the timeout (30 seconds unless `--timeout`, `timeout:` in `apic.yaml` or `# @timeout` says otherwise). **What to do:** Raise --timeout, # @timeout or timeout: in apic.yaml, or check the server. <a id="e303"></a> ### E303 TLS handshake failed Exit 3. The TLS handshake failed: the server's certificate is not trusted, has the wrong name or has expired, or the server refused the client certificate. `--insecure` skips verification for one command, as a last resort. **What to do:** Trust the server's CA with --cacert or tls.caFile, or check the client certificate. <a id="e304"></a> ### E304 protocol problem Exit 3. The server's answer could not be used: it did not negotiate HTTP/2 for a request line that asks for it, the response was malformed, or the body was larger than apic reads. **What to do:** Check the server speaks what the request asks for. <a id="e305"></a> ### E305 cancelled Exit 3. The run was interrupted (Ctrl-C, or `esc` in the UI) while a request, a `# @sleep` or a retry wait was in progress. A flow prints its summary so far, the session and the history keep what the completed requests captured and returned, and `--report` is still written. A second Ctrl-C ends the process at once. **What to do:** Run the command again. ## Validate diagnostics `apic validate` reports problems in the files before anything runs, each with a line, a column and one of these codes (the `code` key of `validate --json`). They are a separate namespace from the E codes above: a file with an error-severity diagnostic refuses to run with [E103](#e103). | Code | Meaning | |---|---| | `ambiguous-step` | a `# @step` phrase that matches the same text as another step | | `bad-assert` | `# @assert` that is not `selector op value` | | `bad-auth` | an `# @auth` spec that does not parse | | `bad-auth-config` | a JetBrains `Security.Auth` configuration in an env file that apic cannot use (not OAuth2, the Implicit grant, a missing Token URL or Client ID) | | `bad-capture` | `# @capture` that is not `name = selector` | | `bad-config-auth` | auth.default in apic.yaml does not parse | | `bad-graphql` | a GraphQL request (GRAPHQL method or X-REQUEST-TYPE: GraphQL) without a query, or whose variables block is not a JSON object | | `bad-header` | a line in the header section that is not `Name: value` | | `bad-http-version` | a request line whose HTTP version is not HTTP/1.1 or HTTP/2 | | `bad-multipart` | a multipart/form-data body without a boundary, or whose parts are not laid out between `--boundary` delimiters | | `bad-name` | `# @name` without a value | | `bad-ref` | a `# @ref` or `# @forceRef` whose target is not one request in the project | | `bad-retry` | a `# @retry` (or retry in apic.yaml) that is not `<attempts> [interval]` | | `bad-save-path` | a `>> file` after the body with no path, a path outside the project, or a second one on the same request | | `bad-sleep` | a `# @sleep` whose value is not a duration such as 500ms or 2s | | `bad-step` | a `# @step` phrase that does not parse | | `duplicate-name` | a request name used more than once in the project | | `editor-script` | an editor-only script or redirect block (skipped, not sent) | | `exec-disabled` | `# @auth exec` without auth.allowExec in apic.yaml | | `missing-body-file` | a `< file` body, or a `< file` part of a multipart body, whose file does not exist | | `missing-schema-file` | a `# @assert … matchesSchema <file>` whose schema file does not exist or lies outside the project | | `orphan-directives` | directives that are not followed by a request line | | `ref-cycle` | a `# @ref` chain that leads back to the request it started from | | `unknown-auth-key` | a field of a `Security.Auth` configuration that apic does not act on | | `unknown-directive` | a `# @directive` apic does not know (ignored) | | `unknown-selector` | a selector that is not status, statusText, duration, header.*, cookie.*, body or body.$*, or a body path apic cannot read | --- # Changelog URL: https://apic.sh/changelog/ What changed in each apic release: new commands, flags and MCP tools, changes to the --json contract, and fixes, newest first. <!-- Generated by scripts/changelog from CHANGELOG.md at the repository root; edit that file and run task docs:changelog. --> What changed for people using apic, release by release. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the versions [Semantic Versioning](https://semver.org/): while apic is 0.x, a minor bump adds a command, a directive, a flag or an MCP tool, and a patch bump fixes something without changing what the binary accepts. Every release's notes on GitHub are its section here, so a change a user would notice gets a line under Unreleased in the pull request that makes it. ## [0.2.0] - 2026-10-27 ### Added - `apic mock <spec>` serves an OpenAPI 3 document as a stateless mock API on localhost, answering from the document's declared responses and examples, so the requests `apic import` wrote can be proved against the contract before the API exists. A `Prefer: code=404` header line asks for another documented response. It proves nothing about the real API: point `baseUrl` at that one when there is one. - `apic mcp install` registers the MCP server in the project's `.mcp.json`, the project-scoped file Claude Code reads from the directory it starts in and the other clients accept in the same shape, with `--dir` and `--env` filled in from `-C` and `--env`. It merges with what the file holds, reports an identical entry as unchanged, refuses a file that is not a JSON object rather than overwriting it, and `--to .cursor/mcp.json` picks Cursor's own file. - `apic init` writes the same `.mcp.json` into a new project, beside the Agent Skill; `--no-mcp` leaves it out, and an entry a team has changed is kept unless `--force`. - Each release publishes apic to the [MCP registry](https://registry.modelcontextprotocol.io/) as `io.github.hungovercoders/apic`, the `ghcr.io/hungovercoders/apic` image running `apic mcp` with the project mounted at `/work`, so an MCP client that installs servers from a catalogue can find it. - The `setup-apic` GitHub Action has a README, with a paragraph for an agent running in the job. ### Changed - A plain (not `--json`) error written to a pipe or a log ends with one more line saying `--json` prints it as one object to branch on, since the reader there is more often a script or an agent than a person. A terminal never shows the line, and `apic ui`, which refuses `--json`, never prints it. ## [0.1.4] - 2026-10-25 ### Added - E201 unknown request and E204 unknown environment suggest the closest known names, in the message and as `suggestions` in the `--json` error object, and every error shows the catalogue's hint under it. - `apic init` and `apic demo` take an empty directory as the target, and every command's `--help` has examples. - In the terminal UI, `E` steps to the previous environment, and the arrow keys move through the list while a filter is being typed. - The licence and third-party notices ship in every archive, package and the image. ### Changed - The user docs moved to [apic.sh](https://apic.sh/), with the course, `llms.txt` and `llms-full.txt` for agents, and a privacy page. ### Fixed - Ctrl-C cancels a run cleanly, with exit 3 and E305, instead of leaving a half-written session. - The terminal UI stops reading the keyboard while an editor it opened runs, and passes `--wait` to VS Code; four rendering fixes, and VT output on the Windows console; keys the filter prompt ignores no longer reset the cursor. - `apic list` lines up its columns across the files of a project and never pads the end of a line. ## [0.1.1] to [0.1.3] - 2026-10-10 The release pipeline only: the Homebrew cask's tap token reached goreleaser. The binary did not change. ## [0.1.0] - 2026-10-10 The first release: `.http` files run from the terminal, CI or an AI agent, with one static binary for Linux, macOS and Windows. - `apic run` with environments from `http-client.env.json`, variables from flags, the shell, the private env file and `.env`, captured values that persist in `.apic/session.json`, `# @ref` dependencies, assertions, retries, polling, redirects that drop credentials and a per-host TLS setting; a file runs in order as a flow. - `--json` output with a stable shape and exit codes 0, 1, 2 and 3, an error catalogue with a code, a hint and a URL for every error, and `--dry-run`, `--body-only`, `--body-limit` and `--redact`. - Authentication: bearer, basic, AWS SigV4 from apic's own signer, OAuth2 client credentials, device code and authorisation code, and a command's output. - `apic test` runs Gherkin features against the project's requests with a built-in vocabulary and `# @step` phrases. - `apic list`, `describe`, `env`, `session`, `history`, `history diff`, `select`, `validate`, `fmt`, `curl`, `snippet` and `import` from OpenAPI 3, Postman collections and curl commands. - `apic mcp`, an MCP server over stdio or HTTP, and `apic lsp`, a language server for any editor; the VS Code extension drives the binary. - `apic ui`, a terminal UI with its own terminal layer, and `apic demo`, an offline API and project to try everything on. - `apic skill` and `apic init` carry the Agent Skill that briefs an AI agent on all of the above. [0.2.0]: https://github.com/hungovercoders/apic/compare/v0.1.4...v0.2.0 [0.1.4]: https://github.com/hungovercoders/apic/compare/v0.1.3...v0.1.4 [0.1.3]: https://github.com/hungovercoders/apic/compare/v0.1.2...v0.1.3 [0.1.1]: https://github.com/hungovercoders/apic/compare/v0.1.0...v0.1.1 [0.1.0]: https://github.com/hungovercoders/apic/releases/tag/v0.1.0 --- # FAQ URL: https://apic.sh/faq/ Short answers to the questions that come up: missing or wrong variables, the session, secrets in CI, AWS, proxies and OAuth2, Gherkin steps, the UI, installing and editors. Short answers to the things that come up. Anything longer lives in the guides these link to. Every error apic prints has a code (`E101`, `E301`, …); the [error catalogue](https://apic.sh/errors/) lists them all with what to do. ## Why does it say a variable is missing? Because nothing provided it. The error names the request that would: ``` error: users.http:14: missing variable {{token}}: it is captured by request "login"; run `apic run login` first, or pass --var token=... E101 missing variable · see https://apic.sh/errors/#e101 ``` `apic describe <id>` shows every variable the request needs, the source each one resolved from, and whether the request is ready to send. The [precedence order](https://apic.sh/cheatsheet/#variable-precedence) decides which source wins. Put `# @ref login` on the request and apic runs `login` itself when the token is missing; see [dependencies](https://apic.sh/format/#dependencies). The code is [E101](https://apic.sh/errors/#e101). ## Why does a variable have the wrong value? Something earlier in the precedence order is providing it. Common culprits: a stale captured value in the session, or an `APIC_VAR_` variable left in the shell. `apic describe <id>` prints the winning source for each variable; `apic session clear` forgets captured values for the current environment. ## Do captured values leak between environments? No. The session stores them per environment, so `dev` and `staging` keep separate tokens. `apic session` lists them grouped by environment, and `apic session clear --all` clears the lot. ## How do I keep secrets out of CI logs? Two things, and use both: - Pass secrets through the shell as `APIC_VAR_<name>` instead of writing them to a file on the runner. - Add `--redact`, which masks header values, bodies, query values and captured values in the output. Sensitive headers (`Authorization`, `Cookie`, API-key headers, and anything whose value came from a secret source) are masked even without it. Recipe: [a smoke test in CI that never leaks secrets](https://apic.sh/cookbook/#a-smoke-test-in-ci-that-never-leaks-secrets). ## My AWS request comes back 403 The signature is computed from the service, region, method, path, query and body, so a 403 usually means one of those does not match what the API expects: - `service=` defaults to `execute-api`. For anything else (`s3`, `lambda`, `es`) say so explicitly. - The region must be the API's region, not your default one. - Check the credentials apic will use: it reads the environment first, then the named profile, then the AWS CLI. `aws sts get-caller-identity --profile <name>` tells you who you are. - An expired SSO session is reported with the CLI's own message, usually "run aws sso login". Details in [authentication](https://apic.sh/auth/#aws). ## How do I send requests through a proxy? `HTTP_PROXY`, `HTTPS_PROXY` and `NO_PROXY` are honoured the way curl honours them. For a proxy that should beat the environment, or one that belongs to a project, set it explicitly: ```sh apic run get-user --proxy http://127.0.0.1:8080 # Burp, mitmproxy, Charles apic run get-user --proxy socks5://127.0.0.1:1080 apic run get-user --no-proxy # ignore every setting for one run ``` ```yaml # apic.yaml proxy: http://proxy.internal:3128 noProxy: [localhost, .internal] ``` `--proxy` beats `apic.yaml`, which beats the environment. Credentials go in the URL (`http://user:pass@proxy:3128`) and are shown as `***` wherever apic reports the proxy: `describe`, `env --json`, `run -v` and `run --json`. Debugging a TLS API through an intercepting proxy also needs its CA: `--cacert mitmproxy-ca.pem`, or `--insecure` for a one-off. A proxy URL apic cannot use is [E207](https://apic.sh/errors/#e207); an untrusted certificate is [E303](https://apic.sh/errors/#e303). ## Can apic do the OAuth2 authorization code flow? Yes, with PKCE: `# @auth oauth2 grant=authorization_code authUrl=... tokenUrl=... clientId=...`. apic listens on a loopback port, opens the sign-in page in your browser, and exchanges the code it gets back; the token is then cached and refreshed like every other grant, so the browser is needed once per refresh-token lifetime. It is a human flow: under `--json`, over MCP or without a terminal apic never opens a browser, and with no cached token the request fails with exit 2 asking you to run it once interactively ([E105](https://apic.sh/errors/#e105)). Providers that offer it may prefer `grant=device_code`, which needs no redirect. See [authentication](https://apic.sh/auth/#authorization-code-with-pkce). ## A Gherkin step comes out undefined The phrase does not match anything apic knows. Run `apic test --steps` to print the built-in vocabulary and every `# @step` phrase the project declares, then make the feature match one of them exactly. Undefined steps fail the run on purpose: a test that silently skips is worse than a red one. ## Can I write my own step definitions? No, and that is deliberate. The vocabulary plus `# @step` phrases on requests is the whole language, which keeps features runnable by anyone with the binary and no project-specific code. When you need logic, put it in a shell script around `apic run --json`. ## Why is there no scripting? Because the moment a request file can compute things, it stops being a file an editor can send and a reader can trust. apic's escape hatches are `--json` for programs, `apic curl` for one-off surgery, and `# @auth exec` for credentials that come from a tool. ## `apic ui` will not start It needs an interactive terminal, and says which condition failed ([E213](https://apic.sh/errors/#e213)): - stdout is a pipe or file: use `apic run` or `apic list --json` instead. - `--json` was given: the UI has no machine output by design. - On Windows, use Windows Terminal or PowerShell; Git Bash's mintty needs `winpty apic ui`. - Below 70x16 it reports the terminal is too small rather than drawing a broken screen. ## Where is the colour? Colour is switched off when stdout is not a terminal, when `NO_COLOR` is set, when `--no-color` is given, and whenever `--json` is used. That is why piping to a file gives clean text with no escape codes. ## Can I pin the version the installer fetches? Yes: ```sh curl -fsSL https://raw.githubusercontent.com/hungovercoders/apic/main/install.sh | APIC_VERSION=v1.2.3 sh curl -fsSL https://raw.githubusercontent.com/hungovercoders/apic/main/install.sh | APIC_INSTALL_DIR=~/bin sh ``` The variable goes before `sh`, not before `curl`: it is the installer that reads it. On Windows, the same variables for `install.ps1`: ```powershell $env:APIC_VERSION = "v1.2.3"; irm https://raw.githubusercontent.com/hungovercoders/apic/main/install.ps1 | iex ``` Both installers download the release archive for your platform, verify it against the published `checksums.txt`, and refuse to install on a mismatch. ## Does apic work with VS Code and JetBrains files? That is the point. apic runs the common subset of the `.http` format shared by VS Code REST Client, JetBrains HTTP Client, kulala.nvim and httpyac, and everything it adds is a `# @directive` comment those tools ignore. `# @note` and `# @prompt` from REST Client are accepted and ignored, so a file that uses them still parses (pass prompted values with `--var`). ## What is not supported? No scripting, no GraphQL schema tooling (a query is sent as the editors write it), no gRPC beyond plain HTTP. The honest full list is in [the comparison](https://apic.sh/comparison/#what-apic-does-not-do-yet), and what will not be added, with the reason and the escape hatch for each, is under [deliberately not planned](https://apic.sh/comparison/#deliberately-not-planned). --- # How apic compares URL: https://apic.sh/comparison/ How apic compares with Taskfile and curl, REST Client and the JetBrains HTTP Client, ijhttp, Kulala.nvim, httpyac, Bruno, Hurl and Postman, honestly, with links to the migration guides. apic is deliberately narrow: run `.http` files anywhere, for humans and agents, from one static binary. This page is an honest look at where that lands against the tools you might otherwise use. To move a project across, see the migration guides: from [Postman](https://apic.sh/migrate/postman/), [Bruno](https://apic.sh/migrate/bruno/), [Hurl](https://apic.sh/migrate/hurl/), [httpyac](https://apic.sh/migrate/httpyac/), and [curl and Taskfile](https://apic.sh/migrate/curl/). ## Summary "Editors" is VS Code REST Client and the JetBrains HTTP Client inside the IDE; `ijhttp` is JetBrains' command-line runner for the same files, and [Kulala.nvim](https://github.com/mistweaverco/kulala.nvim) runs them in Neovim. The other tools' cells follow their own documentation as of September 2026; they move fast, so a correction is a welcome pull request. | | Taskfile + curl | Editors | ijhttp | Kulala.nvim | httpyac | Bruno | Hurl | apic | |---|---|---|---|---|---|---|---|---| | Runs with nothing installed but a binary | curl is everywhere | editor only | needs a JVM (or Docker) | needs Neovim and curl | needs Node | needs Node for the CLI | yes | yes | | Request files editors can send with a click | no | yes (`.http`) | yes (`.http`) | yes (`.http`) | yes (`.http`) | Bruno app / extension (`.bru`) | no | yes (`.http`) | | Environments | shell vars | env files | env files | env files, `.env` | env files, `.env` | yes | `--variables-file` | env files, `.env`, shell, `--var` | | Capture and reuse values | shell plumbing | in-editor only | JS handlers, in one run | request references and scripts, in the editor | yes, in one run | JS scripts, in one run | yes, in one run | yes, and persisted between runs | | Assertions | none | none (JetBrains: JS) | JS (`client.test`) | JS or Lua | yes, plus JS | yes | yes | yes: JSONPath filters, types, length, JSON Schema | | Structured output for programs | curl's | no | JUnit report | no | `--json`, JUnit | reports (JSON, JUnit, HTML) | JSON report | JSON per request, NDJSON for flows, stable error codes | | Discovery (`list`, `describe`) | `task --list` | file tree | no | in the editor | no | GUI | no | yes | | Never prompts | yes | n/a | yes | n/a | picker unless `--all`/`--name` | yes | yes | yes | | MCP server for agents | no | no | no | no | no | no | no | yes | | Gherkin features without a Cucumber runtime | no | no | no | no | no | no | no | yes (`apic test`) | | Data-driven runs | shell loop | no | no | no | `@loop` | CSV and JSON in the CLI | no | yes (`run --data`) | | OpenAPI import | no | no | no | no | no | yes | no | yes | | Postman import | no | no | no | no | no | yes | no | yes (`apic import`, with environments and simple tests) | | curl export and import | is curl | yes | no | yes | extension | GUI | no | yes, plus HTTPie, PowerShell, Python, JavaScript and Go snippets | | Scripting | shell | JetBrains JS | JavaScript | JavaScript, Lua | JavaScript | JavaScript | no | no | | Auth helpers | via curl flags | some | basic, digest, OAuth2 (`Security.Auth`) | via curl, OAuth2 (`Security.Auth`) | OAuth2 (all flows), AWS, basic, digest | OAuth2, AWS, basic, digest | basic, AWS, digest | AWS SigV4 (no SDK), OAuth2 (client credentials, password, device code, authorization code with PKCE; JetBrains `Security.Auth` and `$auth.token`), digest, API key, basic, bearer, exec | | Cookie jar | via curl flags | some | yes | via curl | yes | yes | yes | yes (opt-in, per environment) | | Proxy | `-x` | IDE settings | `--proxy` | via curl | yes | yes | `-x` | yes (`--proxy`, `proxy:` and `noProxy:` in apic.yaml, `HTTP(S)_PROXY`) | | Client certificates, private CAs | via curl flags | JetBrains | `SSLConfiguration` | via curl | yes | yes | yes | yes (`tls:` in apic.yaml, flags, JetBrains `SSLConfiguration`) | | Multipart uploads with file parts | `curl -F` | yes | yes | yes | yes | yes | yes | yes | | HTTP version on the request line | `--http2` | JetBrains | yes | via curl | yes | no | `--http2` | yes (HTTP/1.1, HTTP/2) | | GraphQL, gRPC, WebSocket | curl for GraphQL | GraphQL (JetBrains: all three) | GraphQL, WebSocket | GraphQL, gRPC, WebSocket | GraphQL, gRPC, WS, MQTT, AMQP | yes | GraphQL | GraphQL; the rest are [not planned](#deliberately-not-planned) | | GUI | no | the editor | no | Neovim | VS Code extension | yes | no | terminal UI (`apic ui`) and a VS Code extension | What is coming is tracked in the [epics on GitHub](https://github.com/hungovercoders/apic/issues?q=is%3Aissue+label%3Aepic): [distribution](https://github.com/hungovercoders/apic/issues/1), [the docs](https://github.com/hungovercoders/apic/issues/2) and [the VS Code extension](https://github.com/hungovercoders/apic/issues/3). ## Size A stripped apic binary is about 16 MB, in the same range as `task` or `yq` and well below `gh`, `kubectl` or `terraform`. The largest pieces are the MCP SDK and the Gherkin runner; the OpenAPI importer, the AWS signing and the terminal UI's event loop are written in-tree to keep them small. ## Against Taskfile + curl This is what apic replaces. You keep Task if you like it ([taskfile.md](https://apic.sh/taskfile/)); the requests move out of shell strings into `.http` files. You gain environments, a persisted token, assertions, `--json`, `list`/`describe`, and files an editor can send. You lose nothing: `apic curl` gives the curl back. ## Against VS Code REST Client and JetBrains HTTP Client apic uses their format, so this is not either/or. The editors give humans the click experience; apic gives the same files to the terminal, CI and agents. What the editors have that apic does not: JetBrains' JavaScript response handlers, and the in-editor response viewer. apic reads the common subset and ignores what it does not know, so a file with editor-only features still parses: a `> {% … %}` response handler or a `< {% … %}` pre-request script is skipped rather than sent, and `apic validate` lists what was skipped. A `>> ./file` line, which both editors use to save the response, works the same under apic, and so do JetBrains' `SSLConfiguration` and `Security.Auth` blocks in the env files and `{{$auth.token("name")}}`. ## Against ijhttp `ijhttp` is the JetBrains HTTP Client on the command line: the same files, the same env files, JavaScript handlers and a JUnit report, which makes it the most faithful way to run a JetBrains project in CI. It needs a JVM or the Docker image, keeps no state between invocations, and has no discovery, JSON output or agent integration. apic runs the same files without the JavaScript (handlers are skipped and `apic validate` says so), and reads `SSLConfiguration`, `Security.Auth` and `$auth.token` from the same env files. A project can use both: the IDE and `ijhttp` for the scripted checks, apic for agents and the terminal. ## Against Kulala.nvim Kulala.nvim is the `.http` client for Neovim: it sends through curl, reads the JetBrains env files, chains requests by reference, runs JavaScript or Lua scripts, and reaches gRPC and WebSocket through `grpcurl` and `websocat`. It is an editor experience, like REST Client is for VS Code. apic is not a replacement for it but a partner: the same files run under apic in CI and for agents, and apic's editor notes for Neovim are in [editors.md](https://apic.sh/editors/). ## Against httpyac httpyac is the closest existing tool: it runs the same `.http` files, reads the same `http-client.env.json` and `.env`, and ships a VS Code extension. It is far richer: JavaScript blocks and handlers, `@loop` and `@import`, every OAuth2 flow, AWS and digest auth, GraphQL, gRPC, WebSocket, MQTT and AMQP, JUnit output, and a plugin system. Its `# @ref` and `# @forceRef` mean the same thing in apic. If Node is acceptable everywhere you run requests, take it seriously. apic differs in the ways that matter for agents and locked-down machines: it is one binary with no Node; captured values and tokens persist between invocations; it never opens an interactive picker; it has `list`, `describe` and the missing-variable hints; and it has an MCP server, curl export and OpenAPI import in the CLI. The two can share one project: httpyac in the editor, apic for agents and CI. ## Against Bruno Bruno is a full product: a GUI, JavaScript pre and post request scripts, OAuth2 flows, secret manager integrations, GraphQL, gRPC and WebSocket, CI reporters, and Postman import. If you want all of that, use Bruno. apic's advantages are specific: - **No Node.** The `bru` CLI is an npm package. apic is one binary. - **Editor-native files.** `.bru` needs Bruno or its extension. `.http` is understood by VS Code, JetBrains and Neovim out of the box. - **State between invocations.** `bru run` is stateless; a token set in one run is gone in the next. apic's session keeps captures per environment, which is what an agent issuing one command at a time needs. - **Built for agents.** `list`, `describe`, missing-variable hints, a stable JSON object per request, and an MCP server in the box. If Node is already everywhere and your team lives in the Bruno app, apic's edge is thin. A small MCP wrapper around `bru` would get you part of the agent story. ## Against Hurl Hurl is the closest single-binary alternative: a plain-text format with assertions and captures, fast, well tested, and richer than apic in protocol details. The contract checks Hurl users write (`isInteger`, `count == 3`, a JSON Schema) have apic equivalents: `isInteger`, `length == 3`, `matchesSchema`. If you do not care about the `.http` format, editor support, persisted sessions or MCP, Hurl is a fine choice. apic differs in three ways: the files are standard `.http` and clickable in editors; captures persist between runs; and there is a discovery and MCP layer for agents. Hurl also runs a file top to bottom only, where apic can address one named request. Both retry a request until its assertions pass (Hurl's `[Options] retry:`, apic's `# @retry`). ## Against Postman Postman is a hosted product with collaboration, mocking, monitoring and a cloud workspace. apic is a local file runner: the one of those it has is mocking, and only the stateless kind, where `apic mock openapi.yaml` serves a document's declared responses on localhost so the requests `apic import` wrote from it can run before the API exists; Postman's mock servers are hosted and remember what was sent. The rest of the overlap is only "send a request with variables and check the result", and there apic's answer is plain files in git, no account, no runtime. `apic import collection.postman.json` brings a collection across: folders, requests, variables, environments, auth and the simple `pm.test` checks; pre-request scripts and the rest of the test scripts are listed as notes, since apic has no scripting. Their usual jobs have homes: a computed value comes from `--var` or `APIC_VAR_*`, a token from `# @auth` or a `# @ref` request, a check from `# @assert`. ## What apic does not do yet So you are not surprised later: - OAuth2 is the four common grants (client credentials, password, device code, authorization code with PKCE), AWS SigV4, digest, API keys, basic and command-provided tokens; see [auth.md](https://apic.sh/auth/). Implicit and hybrid flows are not there, and the browser flow is for a person at a terminal, never an agent. - A GraphQL query is sent the way the editors write it (the `GRAPHQL` method or `X-REQUEST-TYPE: GraphQL`, becoming a JSON POST), but there is no GraphQL schema tooling. - Reports are limited to what `apic test` emits (pretty, progress, cucumber JSON, JUnit, HTML) and `run --json` or `run --report`. - Installing is Homebrew on macOS and Linux, `go install`, the install scripts for Linux, macOS and Windows, `.deb`, `.rpm` and `.apk` packages, a Docker image, a release archive or the [GitHub Action](https://apic.sh/getting-started/#7-put-it-in-ci), each shown in [getting started](https://apic.sh/getting-started/#1-install). There is no apt, yum or apk repository, and Scoop, winget and the mise, aqua and asdf registries are still on the [distribution epic](https://github.com/hungovercoders/apic/issues/1). ## Deliberately not planned These come up often enough to answer once. Each would make apic a different tool, so they are not on any roadmap, and each has an escape hatch: | Not planned | Why | Instead | |---|---|---| | Scripting and response handlers | The moment a request file can compute things, it stops being a file an editor can send and a reader can trust. | `--json` into a shell script or `jq`; `# @capture` and `# @assert` for the common jobs; `# @auth exec` for credentials that come from a tool. | | Custom step definitions | The vocabulary plus `# @step` phrases on requests is the whole language, which keeps features runnable by anyone with the binary and no project code. | A `# @step` phrase on a request, or a shell script around `apic run --json`. | | gRPC | Another protocol with its own schema and tooling; apic is an HTTP runner. | `grpcurl`, or Kulala.nvim and httpyac, which drive it. | | WebSocket | A conversation rather than a request and a response, which the `.http` model and the one-result-per-request JSON do not fit. | `websocat`, or the tools above. | | MQTT and AMQP | Messaging, not HTTP. | The broker's own client, or httpyac. | | A GUI beyond the terminal UI and the VS Code extension | The editors already are the GUI for `.http` files; apic's job is everywhere else. | `apic ui`, the [VS Code extension](https://apic.sh/editors/), or any editor that reads `.http`. | | A hosted workspace | apic is plain files in git with no account; collaboration is the repository. | Git, pull requests and CI with the [GitHub Action](https://apic.sh/getting-started/#7-put-it-in-ci). | | A stateful mock | The moment a `POST` changes what a later `GET` returns, the mock needs storage, identity and reset rules, and stops being the spec read back. | `apic demo` for a stateful fake with a known shape; a real backend otherwise. | | Request validation in the mock | Checking a request against its schema is a contract-testing tool with its own error language; apic's checks are `# @assert` on responses. | A `# @assert` on the real API, or [Prism](https://stoplight.io/open-source/prism), which validates both sides. | | Recording and proxying | A mock that records a real API is a capture tool with credentials in the middle of it, which changes what apic has to be careful about. | Point the env file at the real base URL; the mock is only for before the backend exists. | | Dynamic responses, latency and faults | Templated bodies, delays and injected errors are scripting by another door, which is already the first row of this table. | A `Prefer:` header to pick a different documented response; `GET /slow` and `GET /status/{code}` on `apic demo` for timing and failure cases. | --- # Verifying a release URL: https://apic.sh/verifying/ Check an apic release before you trust it: the checksums, the cosign signatures on checksums.txt and the container image, the per-archive SBOMs and the licence notices. Every apic release ships three things that let you check a download before you trust it: | File | What it is | |---|---| | `checksums.txt` | SHA-256 of every archive and every `.deb`, `.rpm` and `.apk` package in the release | | `checksums.txt.sig` + `checksums.txt.pem` | a [cosign](https://docs.sigstore.dev/) signature over `checksums.txt`, and the certificate it was made with | | `<archive>.sbom.json` | an SPDX 2.3 SBOM listing every Go module compiled into that archive | `install.sh` already checks the archive against `checksums.txt` and refuses to install on a mismatch. That catches a corrupted or truncated download. It does **not** prove who produced the release — for that, verify the signature. ## Verify the signature Signing is keyless: there is no apic private key. cosign gets a short-lived certificate from Sigstore's CA, bound to the identity of the GitHub Actions workflow that built the release, and records the signature in a public transparency log. Verifying checks that chain. You need [cosign](https://github.com/sigstore/cosign#installation). ```sh VERSION=v0.2.0 BASE="https://github.com/hungovercoders/apic/releases/download/$VERSION" curl -fsSLO "$BASE/checksums.txt" curl -fsSLO "$BASE/checksums.txt.sig" curl -fsSLO "$BASE/checksums.txt.pem" cosign verify-blob checksums.txt \ --signature checksums.txt.sig \ --certificate checksums.txt.pem \ --certificate-identity-regexp '^https://github\.com/hungovercoders/apic/\.github/workflows/release\.yml@refs/tags/' \ --certificate-oidc-issuer 'https://token.actions.githubusercontent.com' ``` Expect `Verified OK`. The two `--certificate-*` flags are the point of the exercise, so do not drop them: they say *this was signed by the release workflow in this repository, running on a tag*. Without them cosign will happily confirm that **somebody** signed the file. Then check your archive, or package, against the file you just verified: ```sh sha256sum --ignore-missing -c checksums.txt # macOS: shasum -a 256 -c ``` That chain — signature vouches for `checksums.txt`, `checksums.txt` vouches for the archive — is why only one file needs signing. ## Verify the container image The image `ghcr.io/hungovercoders/apic` is signed by the same workflow, keyless, so the same two identity flags apply: ```sh cosign verify ghcr.io/hungovercoders/apic:0.2.0 \ --certificate-identity-regexp '^https://github\.com/hungovercoders/apic/\.github/workflows/release\.yml@refs/tags/' \ --certificate-oidc-issuer 'https://token.actions.githubusercontent.com' ``` cosign prints the verified signatures as JSON, and exits non-zero if there are none from that identity. To pin what you run to what you verified, use the digest it reports: `ghcr.io/hungovercoders/apic@sha256:…`. The image also carries an SBOM attestation, which buildx attached when it built it: ```sh docker buildx imagetools inspect ghcr.io/hungovercoders/apic:0.2.0 --format '{{ json .SBOM }}' ``` ## Read the SBOM Each archive has a matching `<archive>.sbom.json` listing the module versions compiled into it, which is more reliable than reading this repository's `go.mod`: it describes the artifact you actually downloaded. ```sh curl -fsSLO "$BASE/apic_0.2.0_linux_amd64.tar.gz.sbom.json" # What is in it, and at which version? jq -r '.packages[] | "\(.name) \(.versionInfo)"' apic_0.2.0_linux_amd64.tar.gz.sbom.json | sort ``` The module set differs by platform — cobra pulls in `mousetrap` on Windows only — which is why the SBOM is per archive rather than per release. Tools that consume SPDX (Grype, Trivy, Dependency-Track) can scan it directly: ```sh grype sbom:apic_0.2.0_linux_amd64.tar.gz.sbom.json ``` ## Licences Every archive also contains `THIRD_PARTY_NOTICES.md`, reproducing the full licence text of every module compiled into that binary, alongside apic's own `LICENSE`. Regenerate it from a checkout with `task notices`. ## If verification fails A checksum mismatch or a failed signature on a file you downloaded from the releases page is worth reporting — see [SECURITY.md](https://github.com/hungovercoders/apic/blob/main/SECURITY.md). Please do not open a public issue for it. --- # Licence URL: https://apic.sh/licence/ apic is MIT licensed; what that lets you do, and the licences of the modules it ships with. apic is released under the **MIT Licence**. The full text lives in [`LICENSE`](https://github.com/hungovercoders/apic/blob/main/LICENSE) in the repository, and a copy ships inside every release archive and package and in the container image. In short: use it, change it, ship it inside your own products, commercial or not. Keep the copyright notice with any substantial copy of the source, and understand that it comes with no warranty. ## Third-party code apic is a single static binary, so the Go standard library and runtime and the open source modules it is built from travel inside it. Each keeps its own licence. All of them are permissive except three MPL-2.0 modules, whose copyleft is file-level: | Licence | What | |---|---| | MIT | most modules, including godog, gjson, lipgloss and termenv | | BSD-3-Clause | Go itself, `golang.org/x/...`, `github.com/google/uuid`, `spf13/pflag`, `yosida95/uritemplate` | | Apache-2.0 | `spf13/cobra` and `inconshreveable/mousetrap` (cobra's, in the Windows builds) | | MIT and Apache-2.0 | `gopkg.in/yaml.v3` (the parts ported from libyaml are MIT, the rest Apache-2.0) and `modelcontextprotocol/go-sdk` (moving from MIT to Apache-2.0, so its code is under one or the other) | | MPL-2.0 | the HashiCorp modules godog pulls in (`go-memdb`, `go-immutable-radix`, `golang-lru`) | Nothing here is copyleft in a way that reaches your use of apic or your own code: MPL-2.0 applies only to those modules' own files, which apic does not modify. It does ask that anyone who ships them in a binary says where their source is, which the notices file does for every module. `THIRD_PARTY_NOTICES.md` reproduces each licence in full, along with the `NOTICE` and `PATENTS` files some modules ship, and links each module's exact source on the Go module proxy. Every release archive and package contains it, and the container image has it in `/usr/share/doc/apic` beside `LICENSE` and `CA-CERTIFICATES.md`. The image's CA bundle is Mozilla's certificate store (MPL-2.0) as Alpine packages it, and that file names the package and its source. Regenerate the notices from a checkout at any time: ```sh task notices ``` The generator walks the module set for **every** released platform, so the notices are complete whichever archive you downloaded. The VS Code extension is MIT too. It bundles a handful of npm packages (the language client and what it pulls in, under MIT, ISC and BlueOak-1.0.0), and every `.vsix` carries their notices. --- # Privacy URL: https://apic.sh/privacy/ What apic.sh collects (nothing of its own), what Cloudflare keeps as the host, which other services the pages link to, and what the apic CLI sends. apic handles API credentials, so it is worth being plain about what this site does and does not know about you. ## What this site collects Nothing of its own. There are no accounts, forms, cookies or analytics scripts. The site is a set of static pages whose only scripts are its own: the theme picker, the sidebar and the search, which runs entirely in your browser from an index built with the site. The site's [Content-Security-Policy](https://github.com/hungovercoders/apic/blob/main/website/public/_headers) allows scripts from the site itself and a hash of each of those inline scripts, and lets the page connect only to its own origin, so no third-party script or beacon can run or phone home. Fonts are served from this site, not from a font service. ## Hosting The pages are served by [Cloudflare](https://www.cloudflare.com/). Like any host, Cloudflare processes your IP address and browser details to deliver each page. It keeps aggregate traffic statistics (how many requests, from which countries, with which status codes). Per-request logging (Cloudflare's Workers Logs) is switched off for this site, so no record of your individual visit is kept for the maintainer to read. That is what "analytics" means for this site: there is nothing else behind it. Cloudflare's handling of that data is described in its [privacy policy](https://www.cloudflare.com/privacypolicy/). Nothing from it is combined with anything else or used to identify you. ## Other services the pages link to The pages link out, but they do not load anything from anywhere else. - **GitHub.** The repository, the "edit this page" links, the releases and the install script on `raw.githubusercontent.com` that the install instructions pipe to `sh`. GitHub has its [own privacy statement](https://docs.github.com/en/site-policy/privacy-policies/github-general-privacy-statement). - **Editor marketplaces.** The [editors](https://apic.sh/editors/) page links to the Visual Studio Marketplace and Open VSX for the extension. ## The apic CLI `apic` sends requests only where your project tells it to: the APIs your `.http` files name, and the token endpoints an [`@auth`](https://apic.sh/auth/) directive or the `auth:` section of `apic.yaml` names, which receive the credentials that directive configures. It has no telemetry, no update check and no crash reporting. Error messages, the `--json` output and SARIF reports carry links to this site, but the binary never fetches them; the one request a project can cause here is your editor fetching the `apic.yaml` schema that `apic init` points it at, which Cloudflare sees like any other page view. How the CLI stores sessions, cookies and history on your own machine, and how it masks credentials in output, is in the [security policy](https://github.com/hungovercoders/apic/blob/main/SECURITY.md). ## Questions Open an [issue](https://github.com/hungovercoders/apic/issues). This page was last checked against the site's configuration on 24 October 2026.