Skip to content

Mock API: escape response tokens so bodies stay valid JSON - #335

Merged
bryantgillespie merged 1 commit into
robl/mock-api-extensionfrom
bry/mock-api-token-escaping
Nov 6, 2026
Merged

bryantgillespie merged 1 commit into
robl/mock-api-extensionfrom
bry/mock-api-token-escaping

Conversation

@bryantgillespie

Copy link
Copy Markdown
Contributor

Fix for #333 (blocks release).

Tokens were pasted into the response body as raw text, so normal input broke the JSON. When that happened, the router fell back to sending text/plain with the mock's status, so the frontend got a 200 it couldn't parse.

Examples that broke before this change:

  • {"title": "{{body.title}}"} with a title containing " or a newline. The built-in example's create/update responses use this pattern.
  • "{{body.tags}}" with an array.
  • {"id": {{params.id}}} hit with /tasks/abc.

fillTemplate now tracks whether each token sits inside a JSON string:

  • Inside quotes: the value is escaped. Objects and arrays are written as their JSON text. A missing value becomes an empty string, same as before.
  • Where a number goes: numbers, true, false and null are written as they are. Objects and arrays are written as JSON. Other text is quoted. A missing value becomes null.

{"id": {{params.id}}} still gives 5 for /tasks/5. The README token section is updated.

Testing

  • New fillTemplate tests cover quotes, newlines and backslashes, arrays inside and outside quotes, non-numeric params, missing values and escaped quotes in the template.
  • pnpm test (40 tests), pnpm validate and eslint pass.

@robluton robluton left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you!

@bryantgillespie
bryantgillespie merged commit 19641d3 into robl/mock-api-extension Nov 6, 2026
@bryantgillespie
bryantgillespie deleted the bry/mock-api-token-escaping branch November 6, 2026 17:26
bryantgillespie added a commit that referenced this pull request Nov 6, 2026
* move mock-api extension into directus labs

* fix misaligned text and add space below header bar

* Escape mock response tokens so bodies stay valid JSON (#335)

* Fix Mock API matching, import and Studio edge cases (#336)

---------

Co-authored-by: Bryant Gillespie <bryant@directus.io>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants