Stateful Generators
Use the .state dictionary to store dynamic information (like session IDs or temporary credentials) that can be accessed within your request templates via {{ state.key_name }}.
Using Hooks for dynamic updates
You can provide an async hook function to an HTTPGenerator. The hook is called after every HTTP request. It can inspect the httpx.Response and return a HookAction (e.g., "retry" or "continue"). This is useful for handling expiring credentials: if a 401 error occurs, the hook can update generator.state and return "retry" to transparently attempt the request again with the new state.
import rigging as rg
import httpx
async def refresh_token_hook(generator: rg.generator.HTTPGenerator, response: httpx.Response) -> rg.generator.HookAction:
if response.status_code == 401:
# Logic to get new token
new_token = "new-super-secret-token"
generator.state["access_token"] = new_token
return "retry"
return "continue"
stateful_api = rg.HTTPGenerator.for_json_endpoint(
url="https://api.secure.com/v1/live/chat",
hook=refresh_token_hook,
state={"access_token": "initial-token"},
auth={"header": "Authorization", "format": "Bearer {{ state.access_token }}"},
request_body={"query": "$content"},
response={"content_path": "$.data.result"}
)