> For the complete documentation index, see [llms.txt](https://docs.stoobly.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.stoobly.com/guides/how-to-mock-apis/how-to-customize-mocking/customizing-with-lifecycle-hooks.md).

# Customizing with Lifecycle Hooks

## Background

{% content-ref url="/pages/ANLbxIN4T0Q4YF2llfer" %}
[Lifecycle Hooks](/core-concepts/agent/lifecycle-hooks.md)
{% endcontent-ref %}

## Writing a Lifecycle Hooks Script

1. Write a Python script (e.g. lifecycle\_hooks.py)
2. In this script, define the lifecycle events to hook into
3. Define what kind of behavior to execute for each of those events

Below is a sample script that prints some strings during two lifecycle events.

{% hint style="warning" %}
Manipulating the **context** object will affect the behaviour of the request interception.
{% endhint %}

```python
from stoobly_agent.app.proxy.mock.context import MockContext

def handle_before_mock(context: MockContext):
    print('Before mock!')

def handle_after_mock(context: MockContext):
    print('After mock!')
```

* `handle_before_mock` is for **before** a request gets mocked
* `handle_after_mock` is for **after** a request gets mocked

## Enabling Lifecycle Hook Script Use

Pass the path to the lifecycle hooks scripts using the `--lifecycle-hooks-path` option:

```bash
stoobly-agent run --lifecycle-hooks-path ~/path-to-file/lifecycle_hooks.py
```

## Example

```python
from stoobly_agent.app.proxy.mock.context import MockContext

def handle_after_mock(context: MockContext):
    response = context.flow.response
    response.status_code = 401 # Test unauthorized
```
