Architecture¶
How a request flows through apic, which package does what, and the three contracts that every change is checked against. Read this before changing the runner or adding a directive; the last lesson of the course walks the same ground with a keyboard.
The lifecycle of a request¶
flowchart LR
F[".http file"] --> P["parse<br/><code>httpfile</code>"]
P --> D["discover<br/><code>project</code>"]
D --> R["resolve variables<br/><code>runner</code> · <code>template</code> · <code>env</code> · <code>session</code>"]
R --> A["apply auth<br/><code>auth</code>"]
A --> S["send<br/><code>net/http</code>, TLS, cookie jar"]
S --> C["capture and assert<br/><code>selector</code> · <code>assert</code>"]
C --> W["persist<br/><code>session</code>"]
C --> O["render<br/><code>output</code>"]
O --> CLI["<code>apic run</code>"]
O --> UI["<code>apic ui</code>"]
O --> MCP["<code>apic mcp</code>"]
O --> LSP["<code>apic lsp</code>"]
O --> BDD["<code>apic test</code>"]
- Parse (
internal/httpfile). A file is split on###into blocks; each block's comments become directives (# @name,# @assert,# @capture, …), then the request line, headers and body are read. The parser never fails outright: problems become diagnostics with a line, a span and a code, and every request it could read is still there. Multipart bodies are read into parts on demand;apic fmtworks from the same regular expressions so the canonical form and the parser cannot disagree. - Discover (
internal/project). The project root holdsapic.yaml, the env files and.apic/; every*.httpand*.restunder it (or underdir:) is parsed and indexed by name and byfile#N.Validateadds the project-level checks: duplicate names, unknown selectors, bad auth specs,# @refcycles, missing body files. - Resolve (
internal/runner,template,env,session). Every{{placeholder}}in the URL, headers, body and auth spec is looked up in a fixed order:--varandAPIC_VAR_*, values captured in this run, the session, the private env file, the public env file,.env, file@vars, then the built-ins ($uuid,$timestamp, …) and{{name.response.…}}references.describereports the source of each. A missing value stops the request here with exit 2, unless a# @refnames the request that captures it, which runs first. - Apply auth (
internal/auth).# @auth(orauth.default) is parsed into a spec and applied to the outgoing request: a bearer or basic header, an AWS SigV4 signature from apic's own signer, an OAuth2 token fetched and cached in the session, or the output of a command. Credentials are set on the wire and never appear in output. - Send (
net/http). One attempt per# @retryround, with the request's timeout, the TLS settings for its host and the cookie jar when it is on. Redirects drop credential headers when they leave the host. A transport failure is exit 3. - Capture and assert (
internal/selector,internal/assert). The response is read once, bounded bymaxBodyBytes;# @captureselectors pull values out of it and# @assertexpressions are evaluated. A failed assertion or capture is exit 1. - Persist (
internal/session,internal/history). Captures are committed to the run and to.apic/session.jsonfor the environment, and the cookie jar to.apic/cookies.json, so the next invocation continues where this one stopped. Withhistory:set, the result is also kept in.apic/history, in its--jsonform, forapic history. - Render (
internal/output). One set of renderers produces the terminal report, the--jsonline, the UI panes and the MCP result, all from the sameResult, with the same redaction rules.
The three contracts¶
| Contract | Where it is enforced |
|---|---|
The .http dialect stays what VS Code REST Client and JetBrains send. Everything apic adds is a # @directive comment. |
internal/httpfile/testdata/sample.http (the golden parse), TestGrammarMatchesKnownDirectives (the VS Code grammar lists every directive the parser knows), apic validate warning on unknown directives rather than failing. |
--json and exit codes are stable: keys are only added, and 0/1/2/3 keep their meanings. |
runner.ExitCode uses errors.As, so a wrapped TransportError cannot turn a 3 into a 2 (errorlint is on for this); TestExitCodeUnwraps; the JSON shapes in internal/runner are typed and the VS Code extension reads them from types.ts. Error codes (E101…) come from runner.Catalogue, which also generates errors.md; TestEveryCodeIsProduced runs a real command for each. |
Every command is non-interactive and honours --json; apic ui is the one exception and exits 2 without a terminal. |
apic test and the CLI tests run with no TTY; device-code and exec prompts write to stderr and never block on stdin. |
Packages¶
cmd/apic: entry pointinternal/httpfile:.httpparser (AST inast.go, parser inparse.go, multipart bodies inmultipart.go, the formatter informat.go, golden file intestdata/)internal/project: file discovery,apic.yaml, request lookup,validateinternal/env:http-client.env.json, private env file,.env, the JetBrainsSSLConfigurationblockinternal/template:{{placeholder}}substitutioninternal/selector:status,header.x,cookie.x,body.$.pathselectorsinternal/assert: assertion parser and evaluatorinternal/session:.apic/session.jsonpersistence of captured values and cached tokens, and the cookie jar incookies.gointernal/history: the last N responses of each named request per environment in.apic/history, and the comparisonapic history diffand the UI's history tab show (JSON by structure, text by line)internal/auth:# @authspec parsing and application for bearer, basic, AWS SigV4 (own signer insigv4.go, credentials inawscreds.go; no AWS SDK), OAuth2 grants and execinternal/runner: variable precedence, request execution, TLS settings (tls.go), captures, asserts, retries,# @refdependencies, flows,describeinternal/output: the shared theme (theme.go), the string renderers used by both the CLI and the UI (render.go), JSON highlighting (jsonhl.go) and theio.Writerwrappers (output.go)internal/phrase:# @stepphrase to regexinternal/bdd: theapic testmachinery. Godog suite, step vocabulary (steps.go), phrase registration, JSON matching, cucumber-report summaryinternal/lsp:apic lsp, the language server. JSON-RPC 2.0 with the protocol's framing is written out injsonrpc.gorather than taken from a library; diagnostics come fromproject.LoadOverlayandValidateover the open buffers, hover fromDescribe, so an editor sees exactly what the CLI would reportinternal/snippet,internal/curlimport,internal/openapi,internal/postman,internal/mcp: thecurl/snippet,importandmcpcommands. The OpenAPI reader is a small yaml.Node walker (model.go) with local$refresolution and the Postman reader a hand-written model; neither uses a library for its formatinternal/cli: cobra commands, includingdemo,init,fmtanduiinternal/ui: theapic uiterminal UI. Model/update/view live inui.go,list.go,panes.goandrun.go, key bindings inkeys.go, and its own small terminal layer interm.go(input decoding),viewport.goandprogram.go(event loop). Tests driveUpdate/Viewdirectly, so no terminal is neededinternal/demoapi: fake in-memory API (auth, API key, a todos CRUD resource with filtering and validation, polled jobs, multipart upload, GraphQL, a CSV report, a slow route, health; the route list is onNew) and its embedded example project (project/), backing theapic democommand and its test suite. Every route exists so a lesson or a guide has something offline to run against; keep the project's requests andfeatures/todos.featurein step with itexamples/: static sample projects, eachapic validate-checked andapic fmt --check-ed in CI.httpbin(basic/bearer auth, needs network but no keys),github(bearer auth against a real token),spotify(oauth2client-credentials against a real app); the last two need the reader's own credentials in theirhttp-client.private.env.jsoneditors/vscode/: the VS Code extension, TypeScript bundled with esbuild, a thin client over the binary's--jsoncontract (it never parses.httpfiles itself). It injects a grammar for# @directivelines into thehttplanguage REST Client provides rather than owning the language, and bundles the JSON schemas. Released on its ownvscode-v*tagssetup-apic/: the composite GitHub Action (uses: dataGriff/api-caller/setup-apic@v0) that installs a release with the same checksum verification asinstall.sh, on all three runner OSesdocs/: this site (MkDocs Material). The screenshots underassets/are generated from real output byscripts/shot; the course underlearn/is one page per lesson whose marked blocksscripts/learncheckruns in CI;scripts/schemasgenerates the JSON schemas forapic.yaml, the env files and the session file intodocs/schemasandeditors/vscode/schemas;scripts/clidocsgenerates the "Commands and flags" section ofcli.mdand the man pages from the command tree
How to add things¶
Each of these is a checklist the tests enforce, so a missing step fails
task check rather than shipping.
A directive (# @thing value):
- Read it in
internal/httpfile(ast.gofor a typed accessor, orRequest.Directive("thing")), and add it toKnownDirectivesinparse.go; a case intestdata/sample.http. - Add it to the alternation in
editors/vscode/syntaxes/apic-directives.injection.json;TestGrammarMatchesKnownDirectivesfails otherwise. - Give it a rank in
directiveRankinformat.goif it has a natural place in the canonical order. - Act on it in
internal/runner(orinternal/cli), with a test beside the change; avalidatecheck with a code inhttpfile.Codesif it can be wrong. - Document it in the directive table of
format.md, incheatsheet.md, and in the codes table ofcli.mdwhen it has a code.
A Gherkin step: its regex and shapes in internal/phrase/builtin.go,
a handler bound by name in internal/bdd/steps.go, a row in
bdd.Vocabulary, a scenario in bdd_test.go, and the table in
testing.md.
A command: a cobra command in internal/cli (one file per command)
that respects --json, a row in the README table, a section in cli.md,
a line in cheatsheet.md, and task docs:cli to regenerate the flags
reference at the end of cli.md and the man pages (scripts/clidocs;
its staleness test fails otherwise).
An apic.yaml key: a field on project.Config, a description in
scripts/schemas/main.go, and task schemas to regenerate the schemas
(their staleness test fails otherwise).
The repository's own conventions for tests, linting, licensing and releasing are in AGENTS.md and CONTRIBUTING.md.