Insomnia 的 Nunjucks 模板標籤與宣告式規格值比較
Insomnia's Nunjucks Template Tags vs Declarative Spec Values
Insomnia 的 Nunjucks 模板標籤可在請求欄位插入時間戳記、隨機 ID 或變數,但邏輯綁定於客戶端專用語法,不能隨 OpenAPI 合約移植。宣告式規格以資料描述欄位、預設值及限制,讓不同工具讀取和驗證;動態值則由生成器或測試程式碼提供。模板適合臨時請求,應避免用於 API 合約中的業務邏輯。
Quick answer: Insomnia uses Nunjucks template tags to inject dynamic values like timestamps, random IDs, or variables into request fields. They are powerful for ad hoc dynamic requests, but the logic is embedded in a client-specific string syntax that does not travel with an OpenAPI contract. A declarative spec describes values, defaults, and constraints as data, which any tool can read. Use templates for one-off client behavior; prefer declarative values for anything that should be portable and validated.
What a Nunjucks tag looks like
Nunjucks expressions live inside double braces and are evaluated when the request is sent. Insomnia exposes built-in tags for variables, secrets, UUIDs, and timestamps, plus custom extensions.
These tags solve a real problem: a request that needs a unique identifier or current timestamp on every send. The downside is that the dynamic behavior is encoded as a string in a format only this client understands.
| Aspect | Nunjucks template tags | Declarative spec values |
|---|---|---|
| Where logic lives | Inside a request string | In schema, defaults, and examples |
| Portability | Tied to the client | Readable by any OpenAPI tool |
| Validation | Evaluated at send time | Types and constraints are explicit |
| Dynamic generation | Rich built-in functions | Handled by generators or test code |
| Review in git | String expressions are harder to diff | Plain structured data |
Declarative values in the contract
An OpenAPI schema expresses what a field is, whether it is required, its default, and any constraints, rather than how a particular client should generate it. A unique order ID, for example, is described as a string with a format; the client or test harness supplies the actual UUID.
The behavior that a Nunjucks tag performs is now split into two portable parts: the contract declares the shape, while a small generator or test helper produces the dynamic value in ordinary code.
const order = { client_order_id: crypto.randomUUID(), created_at: new Date().toISOString(), currency: process.env.ORDER_CURRENCY || 'USD', note: defaultNote, };
Why embedding logic in strings is risky
When dynamic behavior is hidden inside a template string, static tools cannot see it. A linter cannot check that the generated UUID matches the declared format, and a diff in version control shows a string change rather than a logic change. Templates can also fail silently at send time with a rendering error or an empty value, and the failure depends on the client's available extensions. Declarative data keeps the contract as the single source of truth so a generated client, a mock server, and a test suite all read the same definition.
Where templates remain the right tool
Nunjucks shines for quick, exploratory work where you need a timestamp or a random value for a single manual request and do not want to maintain a spec. It is also convenient for client-specific conveniences that genuinely do not belong in the contract, such as selecting a local environment variable. The rule is to keep templates out of the canonical definition of an API and use them at the edges where a human is driving the client. If a tag starts to encode real business logic, move that logic into code or the contract where it can be tested and reviewed.
Migrating template-heavy requests to a spec
For each tag, ask what it is really producing. A UUID or timestamp maps to a schema format plus a generator; an environment reference maps to configuration injected at runtime; a chained value from a previous response maps to a generated client flow that passes data between calls. Replacing the tags this way removes the client lock-in and makes the requests runnable in CI without a GUI. An AI agent can help by reading the request and proposing the schema and the generator, but verify each field against the real responses so the migration does not silently change behavior.
Testing and linting the migrated behavior
Once a template is replaced by a schema plus a generator, the behavior becomes testable in ordinary code. Assert that the generated UUID matches the declared format, that the timestamp parses as a valid date, and that a missing environment variable falls back to the documented default rather than producing an empty string. These checks can run in CI without launching the client, which is the practical payoff of moving logic out of string tags: failures surface as ordinary test errors with clear messages rather than as a request that renders incorrectly at send time.
Frequently asked questions
Are Nunjucks tags a bad feature?
No. They are useful for dynamic, ad hoc requests and environment references. The risk is encoding portable business logic in a client-specific string syntax instead of the OpenAPI contract.
How do I generate a UUID without a template tag?
Declare the field as a string with format: uuid and have the client or test generate it with a standard library call. The contract defines the shape; ordinary code supplies the value.
Can template tags be validated?
They are evaluated at send time, so static tools cannot reason about the output as easily as declarative schema. Values described in the contract can be type-checked and linted before any request runs.
What about values pulled from a previous response?
Model those as a generated client flow or explicit test steps that pass data between calls, rather than relying on a client's internal tag to extract and store the value. That keeps the sequence portable and reviewable.
This is part of the Powerduck vs Insomnia: API Client and Contract Testing — start there for the full comparison of client-side scripting and declarative, spec-driven workflows.
來源:DEV Community · dev.to