Fill Placeholders in a Chained Request Template
StringsAuto-graded · 18 test casesLast updated
Recursively resolve {{dotted.path}} placeholders in a nested request, keeping native types for whole-string matches and stringifying embedded ones.
Fill Placeholders in a Chained Request Template
A workflow runner sends several HTTP requests in order. Later requests reuse values (IDs, amounts, flags) returned by earlier ones. Those values are kept in a nested dictionary called the context, and each request is written as a template containing placeholders.
Implement fill_request_placeholders(request, context). It returns a new request in which every placeholder has been replaced by the value it refers to in context.
Placeholder format
- A placeholder is written
{{path}}, wherepathis one or more segments joined by.. - Each segment consists only of letters, digits, and underscores (
[A-Za-z0-9_]+). - The path describes nested lookup in
context. For example,{{customer.default_source}}refers tocontext["customer"]["default_source"]. - The braces must hug the path exactly. Text such as
{{ a }},{{a..b}}, or{{}}is not a placeholder and is left as ordinary text.
Replacement rules
- Whole-string placeholder. If a string consists of exactly one placeholder and nothing else (for example
"{{payment.amount}}"), the string is replaced by the resolved value itself, with its original type. The value may be an integer, float, boolean,None, string, list, or dictionary. - Embedded placeholders. In any other string (placeholders mixed with other text, or several placeholders), each placeholder is replaced by Python's
str()of its resolved value, and the result is a string. For instance,"/v1/customers/{{customer.id}}/cards"becomes"/v1/customers/cus_1/cards". A string with no placeholders is returned unchanged. - Substitution is single-pass. Text that comes from a resolved value is never scanned again for placeholders.
Traversal
- The request is a dictionary that contains
"url"(a string) and may also contain"headers"(a dictionary of strings) and"body"(any JSON-compatible value: dictionary, list, string, number, boolean, orNone). - Walk the whole request recursively. Every string value found inside dictionaries and lists, at any depth, is processed by the rules above. Numbers, booleans, and
Noneare left as they are. - Dictionary keys are never modified.
- Keys that are absent from the input must not appear in the output (do not add
headersorbody). - The input
requestandcontextmust not be modified.
Missing values
If a placeholder's path cannot be resolved in context (a segment is missing, or an intermediate value along the path is not a dictionary), raise KeyError. A key that exists with the value None counts as present.
Input and output
request: dict as described above.context: nested dict of runtime values.- Returns: a new dict with the same structure as
request, with all placeholders filled in.
Constraints
- The request nests at most 10 levels deep.
- Context keys match
[a-zA-Z0-9_]+. - A string may contain zero, one, or several placeholders.
- Whole-string placeholders may resolve to falsy values (
0,False,None,"",{},[]); these must be returned as they are.
Examples
Example 1
Input: fill_request_placeholders({'url': '/v1/charges/{{charge.id}}/refund', 'headers': {'Idempotency-Key': 'refund-{{charge.id}}'}, 'body': {'amount': '{{charge.amount}}', 'metadata': {'customer': '{{charge.customer.id}}', 'full_refund': '{{charge.metadata.is_full}}'}}}, {'charge': {'id': 'ch_12345', 'amount': 2500, 'customer': {'id': 'cus_9999'}, 'metadata': {'is_full': True}}})
Output: {'url': '/v1/charges/ch_12345/refund', 'headers': {'Idempotency-Key': 'refund-ch_12345'}, 'body': {'amount': 2500, 'metadata': {'customer': 'cus_9999', 'full_refund': True}}}
Example 2
Input: fill_request_placeholders({'url': '/v1/customers/{{customer.id}}', 'body': {'active': '{{customer.active}}', 'metadata': ['{{customer.name}}', 'hello {{customer.id}}']}}, {'customer': {'id': 'cus_1', 'active': True, 'name': 'Ada'}})
Output: {'url': '/v1/customers/cus_1', 'body': {'active': True, 'metadata': ['Ada', 'hello cus_1']}}
Hints
Hint 1
Handle each kind of node separately: dict, list, string, and everything else. Only strings need any real work.
Hint 2
Use one regex for a placeholder. If the pattern matches the entire string, return the looked-up value as it is; otherwise use a substitution with a callback that converts each looked-up value to a string.
Hint 3
Resolve a path by walking the context one segment at a time, raising KeyError when the current value is not a dict or lacks the segment. Test with `in`, not truthiness, so values like 0, False, and None still work.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a recursive transformation of a JSON-like tree. Only string leaves need real work.
- Recurse over the structure. Dictionaries produce new dictionaries (keys are copied as they are, values are processed), lists produce new lists, and numbers, booleans, and
Noneare returned as they are. - Handle strings with one regex. The pattern is
\{\{([A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*)\}\}.- If the pattern matches the entire string (
fullmatch), return the looked-up value itself. This keeps2500as an int,Trueas a bool, and dicts or lists as structures. - Otherwise run
re.subwith a callback that looks up each placeholder and insertsstr(value). A string with no placeholders passes through unchanged.
- If the pattern matches the entire string (
- Resolve a path by splitting on
.and walking the context one segment at a time. If the current value is not a dict, or the segment is not in it, raiseKeyError. Membership is tested within, so a storedNone,0, orFalseis handled correctly.
Why it is correct
fullmatchsucceeds only when the string is a single placeholder from start to end. Strings like"refund-{{id}}"or"{{a}}{{b}}"fail it and fall into the embedded case, which matches the required behavior.re.subscans the original string once, so text produced by a substitution is never re-expanded.- Malformed placeholders such as
{{ a }}do not match the pattern and remain literal text, as the statement requires. - Because every container is rebuilt and returned values are deep-copied, the input request and the context are never mutated or aliased by the output.
- Dictionary keys and absent optional fields are never touched, so the output has the same shape as the input.
Complexity
Let S be the total size of the request (nodes plus characters), P the number of placeholders, d the longest path length, and V the total size of values copied from the context.
- Time: O(S + P·d + V)
- Space: O(S + V) for the output, plus O(depth) recursion stack (at most about 10 levels here).
Reference solution
import copy
import re
from typing import Any
_PLACEHOLDER = re.compile(r"\{\{([A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)*)\}\}")
def fill_request_placeholders(request: dict, context: dict) -> dict:
def resolve(path: str) -> Any:
current: Any = context
for segment in path.split("."):
if not isinstance(current, dict) or segment not in current:
raise KeyError(path)
current = current[segment]
return current
def fill(node: Any) -> Any:
if isinstance(node, str):
whole = _PLACEHOLDER.fullmatch(node)
if whole:
return copy.deepcopy(resolve(whole.group(1)))
return _PLACEHOLDER.sub(lambda m: str(resolve(m.group(1))), node)
if isinstance(node, dict):
return {key: fill(value) for key, value in node.items()}
if isinstance(node, list):
return [fill(item) for item in node]
return node
return fill(request)