---
title: API
description: Configure Caddy through its admin API, with helpers for TLS and reverse-proxy
  routes
---
<!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->

## How it works

fastcaddy reads and changes Caddy's JSON configuration through the [admin API](https://caddyserver.com/docs/api). It does not edit Caddyfiles. The default API address is `http://localhost:2019`.

You can configure Caddy at two levels:

- Read or change configuration by path with [`gcfg`](core.md#gcfg)/[`pcfg`](core.md#pcfg), or by `@id` with [`gid`](core.md#gid)/[`pid`](core.md#pid).
- Helpers such as [`setup_caddy`](core.md#setup_caddy) and [`add_reverse_proxy`](core.md#add_reverse_proxy) configure TLS and routes. Each helper documents what it replaces or leaves unchanged.

Arrange how to restore the configuration after a Caddy restart. Our production apps run a setup script on each deploy inside `with rollback():`: call [`reset()`](core.md#reset), then add the required configuration. [`reset()`](core.md#reset) clears everything except `admin` by default, and [`rollback()`](core.md#rollback) restores the prior configuration if anything raises mid-script.

Route helpers use these `@id` values to find existing routes:

- A reverse proxy uses its hostname.
- A wildcard route uses `wildcard-{domain}`.
- A subdomain proxy uses `{subdomain}.{domain}`.

Use [`del_id`](core.md#del_id) to remove a route by ID.

```python
from fastcore.test import *
```

## Admin API primitives

`/config/` addresses configuration by path. `/id/` finds an object by its `@id` value anywhere in the configuration.

The admin API location comes from the `CADDY_ADMIN` env var if set. To point somewhere else at runtime, set `fastcaddy.core.admin_url` directly.

[source](https://github.com/AnswerDotAI/fastcaddy/blob/main/fastcaddy/core.py#L27)

### get\_id

```python
def get_id(
    path
):
```

*Get an ID full URL from a path*

```python
get_id('jph.answer.ai')
```

```output
'http://localhost:2019/id/jph.answer.ai/'
```

[source](https://github.com/AnswerDotAI/fastcaddy/blob/main/fastcaddy/core.py#L32)

### get\_path

```python
def get_path(
    path
):
```

*Get a config full URL from a path*

```python
get_path('/apps/tls/automation/policies')
```

```output
'http://localhost:2019/config/apps/tls/automation/policies/'
```

Connection errors include the admin API address. HTTP errors include Caddy's error detail. [`_req`](core.md#_req) adds these notes to the original exceptions before raising them.

[source](https://github.com/AnswerDotAI/fastcaddy/blob/main/fastcaddy/core.py#L55)

### gid

```python
def gid(
    path:str='/'
):
```

*Get the config object whose `@id` matches `path`*

[source](https://github.com/AnswerDotAI/fastcaddy/blob/main/fastcaddy/core.py#L60)

### has\_id

```python
def has_id(
    id
):
```

*Check if `id` is set up*

[source](https://github.com/AnswerDotAI/fastcaddy/blob/main/fastcaddy/core.py#L67)

### gcfg

```python
def gcfg(
    path:str='/'
):
```

*Get the config at `path`*

[source](https://github.com/AnswerDotAI/fastcaddy/blob/main/fastcaddy/core.py#L72)

### has\_path

```python
def has_path(
    path
):
```

*Check if any config exists at `path`*

[source](https://github.com/AnswerDotAI/fastcaddy/blob/main/fastcaddy/core.py#L78)

### pid

```python
def pid(
    d, path:str='/', method:str='post'
):
```

*Put/post config `d` to the object whose `@id` matches `path`*

[source](https://github.com/AnswerDotAI/fastcaddy/blob/main/fastcaddy/core.py#L83)

### pcfg

```python
def pcfg(
    d, path:str='/', method:str='post'
):
```

*Put/post config `d` at `path`*

`method` selects a Caddy admin API operation:

- `post` sets a value, or appends to an array.
- `put` creates a value and any missing parent paths. An existing object key causes HTTP 409.
- `patch` replaces an existing value.
- `delete` removes a value.

Reading a missing key under an existing object returns `null`. Traversing through a missing key fails. [`has_path`](core.md#has_path) treats `None` as absence.

Posting to `/` replaces the entire configuration. [`reset`](core.md#reset) clears the configuration while preserving `admin` by default. [`nested_setcfg`](core.md#nested_setcfg) also writes the entire document after modifying the requested path.

[source](https://github.com/AnswerDotAI/fastcaddy/blob/main/fastcaddy/core.py#L88)

### reset

```python
def reset(
    keep_admin:bool=True
):
```

*Erase the caddy config, preserving `admin` by default*

[`reset`](core.md#reset) clears the configuration while preserving any `admin` section (pass `keep_admin=False` to erase `admin` too).

```python
reset()
gcfg()
```

```python
{}
```

[source](https://github.com/AnswerDotAI/fastcaddy/blob/main/fastcaddy/core.py#L96)

### rollback

```python
def rollback():
```

*Restore the prior Caddy config if an exception occurs inside the block*

[`rollback()`](core.md#rollback) snapshots the current config and restores it if an exception occurs inside the block, so a failed setup script does not leave Caddy wiped after [`reset()`](core.md#reset).

```python
pcfg({}, '/apps/http', method='put')
with expect_fail(RuntimeError, contains='boom'):
    with rollback():
        reset()
        raise RuntimeError('boom')
test_eq(has_path('/apps/http'), True)
reset()
```

## Config tree helpers

[source](https://github.com/AnswerDotAI/fastcaddy/blob/main/fastcaddy/core.py#L105)

### nested\_setdict

```python
def nested_setdict(
    sd, value, *keys
):
```

*Returns `sd` updated to set `value` at the path `keys`*

```python
nested_setdict({'a':'b'}, {'c':'d'}, 'apps', 'http', 'servers', 'srv0')
```

```output
{'a': 'b', 'apps': {'http': {'servers': {'srv0': {'c': 'd'}}}}}
```

[source](https://github.com/AnswerDotAI/fastcaddy/blob/main/fastcaddy/core.py#L113)

### path2keys

```python
def path2keys(
    path
):
```

*Split `path` by '/' into a list*

```python
path2keys('/apps/tls/automation/policies')
```

```output
['apps', 'tls', 'automation', 'policies']
```

[source](https://github.com/AnswerDotAI/fastcaddy/blob/main/fastcaddy/core.py#L118)

### keys2path

```python
def keys2path(
    *keys
):
```

*Join `keys` into a '/' separated path*

```python
keys2path('apps', 'tls', 'automation', 'policies')
```

```output
'/apps/tls/automation/policies'
```

[source](https://github.com/AnswerDotAI/fastcaddy/blob/main/fastcaddy/core.py#L123)

### nested\_setcfg

```python
def nested_setcfg(
    value, *keys
):
```

*Set `value` at the path `keys` in the live caddy config*

[source](https://github.com/AnswerDotAI/fastcaddy/blob/main/fastcaddy/core.py#L129)

### init\_path

```python
def init_path(
    path
):
```

*Create `path` (and any missing parents) as an empty object, if not already present*

[`init_path`](core.md#init_path) creates missing parents and leaves an existing path unchanged.

```python
init_path('/apps/tls/automation')
init_path('/apps/tls/automation')
test_eq(has_path('/apps/tls/automation'), True)
gcfg()
```

```python
{'apps': {'tls': {'automation': {}}}}
```

## TLS automation

Caddy's [automation policies](https://caddyserver.com/docs/json/apps/tls/automation/) control certificate issuance. Two helpers configure the first policy under `/apps/tls/automation`:

- [`add_acme_config`](core.md#add_acme_config) uses ACME with Cloudflare DNS challenges.
- [`add_tls_internal_config`](core.md#add_tls_internal_config) uses Caddy's internal CA for local development.

Both are idempotent when called again with the same policy, and raise `ValueError` if `/apps/tls/automation` already has a different policy so mismatched settings or wrong call order are never silently ignored. Neither modifies configuration outside `/apps/tls/automation`.

```python
cf_token = os.environ.get('CADDY_CF_TOKEN', 'XXX')
```

[source](https://github.com/AnswerDotAI/fastcaddy/blob/main/fastcaddy/core.py#L140)

### get\_acme\_config

```python
def get_acme_config(
    token
):
```

*An ACME issuer config using cloudflare DNS challenges with `token`*

The issuer config that [`add_acme_config`](core.md#add_acme_config) installs:

```python
get_acme_config('some-token')
```

```output
{'module': 'acme',
 'challenges': {'dns': {'provider': {'name': 'cloudflare',
    'api_token': 'some-token'}}}}
```

[source](https://github.com/AnswerDotAI/fastcaddy/blob/main/fastcaddy/core.py#L156)

### add\_tls\_internal\_config

```python
def add_tls_internal_config():
```

*Set up a TLS automation policy using caddy's internal CA (no-op if already identical)*

[source](https://github.com/AnswerDotAI/fastcaddy/blob/main/fastcaddy/core.py#L161)

### add\_acme\_config

```python
def add_acme_config(
    cf_token, subjects=None
):
```

*Set up a TLS automation policy using ACME with cloudflare DNS challenges (no-op if already identical)*

Configure ACME with a valid Cloudflare API token:

```python
add_acme_config(cf_token)
```

For local development, use the internal CA instead:

```python
reset()
add_tls_internal_config()
gcfg(automation_path)
```

```python
{'policies': [{'issuers': [{'module': 'internal'}]}]}
```

Re-calling [`add_tls_internal_config`](core.md#add_tls_internal_config) is a no-op, while calling [`add_acme_config`](core.md#add_acme_config) over an existing internal policy raises `ValueError` instead of silently ignoring it. After a reset, [`add_acme_config`](core.md#add_acme_config) requires a non-blank token.

```python
add_tls_internal_config()
test_fail(lambda: add_acme_config(cf_token), contains='reset()')
reset()
test_fail(lambda: add_acme_config('  '), contains='required')
```

## Schema reference

The package includes Caddy's JSON schema. [`search_schema`](core.md#search_schema) finds matching keys and values. Pass a returned path to [`get_schema`](core.md#get_schema) to read that node. Paths represent list indices as `[n]`.

[source](https://github.com/AnswerDotAI/fastcaddy/blob/main/fastcaddy/core.py#L174)

### caddy\_docs

```python
def caddy_docs():
```

*The caddy JSON schema, loaded (once) from the bundled `caddy_schema.json`*

[source](https://github.com/AnswerDotAI/fastcaddy/blob/main/fastcaddy/core.py#L183)

### get\_schema

```python
def get_schema(
    path:str
):
```

*Get the caddy schema node at `path` (e.g. '/definitions/tls/properties/automation' or a path from [`search_schema`](core.md#search_schema))*

[source](https://github.com/AnswerDotAI/fastcaddy/blob/main/fastcaddy/core.py#L202)

### search\_schema

```python
def search_schema(
    term:str, path:str='', max_results:int=20
):
```

*Recursively search the caddy schema for keys/values containing `term`; returned paths work with [`get_schema`](core.md#get_schema)*

```python
search_schema('on_demand', max_results=3)
```

```output
[('key', '/definitions/tls/properties/automation/properties/on_demand'),
 ('value',
  '/definitions/tls/properties/automation/properties/on_demand/description',
  'on_demand: object\nModule: tls\nhttps://pkg.go.dev/github.com/caddyserver/caddy/v2/modules/caddytls#OnDemandConfig\nOn-Demand TLS defers certificate operations to the\nmoment they are needed, e.g. during '),
 ('value',
  '/definitions/tls/properties/automation/properties/on_demand/markdownDescription',
  'on_demand: `object`  \nModule: `tls`  \n[godoc](https://pkg.go.dev/github.com/caddyserver/caddy/v2/modules/caddytls#OnDemandConfig)  \nOn-Demand TLS defers certificate operations to the\nmoment they are n')]
```

Check returned paths, including list indices, with [`get_schema`](core.md#get_schema).

```python
res = search_schema('issuers', max_results=50)
assert any('[' in p for _,p,*_ in res)
for _,p,*_ in res: get_schema(p)
get_schema(search_schema('on_demand')[0][1])['description']
```

```output
"on_demand: object\nModule: tls\nhttps://pkg.go.dev/github.com/caddyserver/caddy/v2/modules/caddytls#OnDemandConfig\nOn-Demand TLS defers certificate operations to the\nmoment they are needed, e.g. during a TLS handshake.\nUseful when you don't know all the hostnames at\nconfig-time, or when you are not in control of the\ndomain names you are managing certificates for.\nIn 2015, Caddy became the first web server to\nimplement this experimental technology.\n\nNote that this field does not enable on-demand TLS;\nit only configures it for when it is used. To enable\nit, create an automation policy with `on_demand`.\n\n\nOnDemandConfig configures on-demand TLS, for obtaining\nneeded certificates at handshake-time. Because this\nfeature can easily be abused, Caddy must ask permission\nto your application whether a particular domain is allowed\nto have a certificate issued for it.\n"
```

## Routes and reverse proxies

The route helpers use an HTTP server named `srv0`. [`init_routes`](core.md#init_routes) creates it on port 443 when no servers exist (Caddy adds port 80 HTTP-to-HTTPS redirects automatically). Routes go in `/apps/http/servers/srv0/routes`.

[source](https://github.com/AnswerDotAI/fastcaddy/blob/main/fastcaddy/core.py#L212)

### init\_routes

```python
def init_routes():
```

*Create the basic http server config (`srv0` on port 443), if no servers exist yet*

[source](https://github.com/AnswerDotAI/fastcaddy/blob/main/fastcaddy/core.py#L220)

### setup\_pki\_trust

```python
def setup_pki_trust(
    install_trust
):
```

*Configure PKI certificate authority trust installation*

[source](https://github.com/AnswerDotAI/fastcaddy/blob/main/fastcaddy/core.py#L228)

### setup\_caddy

```python
def setup_caddy(
    cf_token=None, # Cloudflare API token (required unless `local`)
    local:bool=False, # Use caddy's internal CA instead of ACME (for local dev)
    install_trust:bool=None, # Install the local CA into the system trust store?
    subjects=None, # Subject names to restrict ACME cert issuance to
):
```

*Create TLS automation config and the http server skeleton*

[`setup_caddy`](core.md#setup_caddy) configures TLS automation and initializes `srv0`. It uses ACME by default or the internal CA with `local=True`. `install_trust` controls installation of the local CA in the system trust store.

```python
setup_caddy(cf_token, subjects=['*.example.com', 'example.com'])
```

Use the internal CA for the remaining local examples:

```python
setup_caddy(local=True)
gcfg(srvs_path)
```

```python
{'srv0': {'listen': [':80', ':443'], 'protocols': ['h1', 'h2'], 'routes': []}}
```

A route's `handle` list contains its handlers. [`encode_handler`](core.md#encode_handler) builds response compression configuration. [`proxy_handler`](core.md#proxy_handler) builds reverse-proxy configuration. You can combine them with other handlers in a custom route.

[source](https://github.com/AnswerDotAI/fastcaddy/blob/main/fastcaddy/core.py#L242)

### encode\_handler

```python
def encode_handler():
```

*An `encode` handler that compresses responses with zstd or gzip*

[source](https://github.com/AnswerDotAI/fastcaddy/blob/main/fastcaddy/core.py#L252)

### proxy\_handler

```python
def proxy_handler(
    *upstreams, # Upstream dial addresses, e.g. 'localhost:5001'
    st_delay:str='1m', # Keep streaming connections open this long across config reloads (None to disable)
    header=None, # Header whose value pins requests to one upstream
    cookie:bool | str | dict=None, # Sticky cookie policy (`True` for Caddy default `lb`, cookie name `str`, or policy `dict`)
):
```

*A `reverse_proxy` handler dialing `upstreams`*

Build handlers without changing Caddy's configuration. Pass `header` to pin matching header values or `cookie` (`True`, a cookie name, or a policy dict) to pin browser sessions to one upstream.

```python
plain = proxy_handler('localhost:5001')
test_eq(plain, dict(handler='reverse_proxy', upstreams=[dict(dial='localhost:5001')], stream_close_delay='1m'))
sticky = proxy_handler('localhost:5001', 'localhost:5002', header='Authorization')
test_eq(sticky, plain | dict(upstreams=[dict(dial='localhost:5001'), dict(dial='localhost:5002')],
    load_balancing=dict(selection_policy=dict(policy='header', field='Authorization'))))
test_eq(proxy_handler('localhost:5001', 'localhost:5002', cookie=True)['load_balancing']['selection_policy'], dict(policy='cookie'))
test_eq(proxy_handler('localhost:5001', 'localhost:5002', cookie='app_lb')['load_balancing']['selection_policy'], dict(policy='cookie', name='app_lb'))
test_fail(lambda: proxy_handler('localhost:5001', header='Authorization', cookie=True), contains='add_reverse_proxy')
sticky
```

[source](https://github.com/AnswerDotAI/fastcaddy/blob/main/fastcaddy/core.py#L269)

### add\_route

```python
def add_route(
    route
):
```

*Append `route` to `srv0`'s route list*

[source](https://github.com/AnswerDotAI/fastcaddy/blob/main/fastcaddy/core.py#L275)

### del\_id

```python
def del_id(
    id
):
```

*Delete every config object whose `@id` matches `id` (e.g. a host)*

[source](https://github.com/AnswerDotAI/fastcaddy/blob/main/fastcaddy/core.py#L280)

### add\_reverse\_proxy

```python
def add_reverse_proxy(
    from_host, # Hostname to match and use as route `@id`
    to_url, # Upstream address or list of addresses, e.g. 'localhost:5001'
    st_delay:str='1m', # Keep streaming connections open this long across config reloads (None to disable)
    encode:bool=True, # Compress responses with zstd or gzip?
    header=None, # Header whose value pins requests to one upstream
    cookie:bool | str | dict=None, # Sticky cookie policy for requests, or fallback when `header` is absent
):
```

*Create (or replace in place) a route reverse-proxying `from_host` to `to_url`, tagged with `@id` `from_host`*

```python
host = 'foo.example.com'
```

```python
add_reverse_proxy(host, "localhost:5001")
gid(host)
```

```python
{ '@id': 'foo.example.com',
  'handle': [{'encodings': {'gzip': {'level': 1}, 'zstd': {'level': 'fastest'}}, 'handler': 'encode', 'prefer': ['zstd', 'gzip']}, {'handler': 'reverse_proxy', 'stream_close_delay': '1m', 'upstreams': [{'dial': 'localhost:5001'}]}],
  'match': [{'host': ['foo.example.com']}],
  'terminal': True}
```

Calling the helper again replaces the host's route in place, keeping its position ahead of trailing wildcard or catch-all routes. `to_url` accepts one upstream address or a list. Set `header='Authorization'` to pin API keys, `cookie=True` to pin browser sessions, or both to pin requests carrying the header by header and everything else by cookie (using a `subroute` inside the same `@id` because Caddy panics when `cookie` is nested as a `header` fallback).

```python
add_route({'@id': 'catch-all', 'terminal': True, 'handle': [proxy_handler('localhost:9999')]})
n = len(gcfg(rts_path))
add_reverse_proxy(host, "localhost:8000")
test_eq(len(gcfg(rts_path)), n)
test_eq([r['@id'] for r in gcfg(rts_path)][:2], [host, 'catch-all'])
test_eq(gid(host).handle[1].upstreams[0].dial, 'localhost:8000')
add_reverse_proxy(host, ["localhost:5001", "localhost:5002"], header="Authorization", cookie=True)
test_eq(len(gcfg(rts_path)), n)
test_eq(gid(host).handle[1].handler, 'subroute')
del_id('catch-all')
```

[`del_id`](core.md#del_id) removes the object matching the ID.

```python
del_id(host)
test_eq(has_id(host), False)
```

### On-demand TLS

Caddy obtains certificates during the TLS handshake for customers who point their own domains at your app.

The permission endpoint lets you prevent strangers from obtaining certificates through your server. Caddy sends it `GET {endpoint}?domain={domain}` before issuing a certificate. Return HTTP 200 to authorize the domain. `tools/testverify.py` provides a minimal FastHTML example.

[`add_on_demand_tls`](core.md#add_on_demand_tls) sets the permission endpoint. It appends an `on_demand: true` policy if none exists, preserving existing policies.

The appended policy has no `subjects` restriction. Caddy rejects a configuration with two unrestricted policies. Restrict earlier policies with `subjects`, as in this setup:

[source](https://github.com/AnswerDotAI/fastcaddy/blob/main/fastcaddy/core.py#L301)

### add\_on\_demand\_tls

```python
def add_on_demand_tls(
    endpoint
):
```

*Enable on-demand TLS, asking `endpoint` for permission before each cert is issued*

```python
setup_caddy(cf_token, subjects=["*.example.com", "example.com"])
add_on_demand_tls("http://localhost:5431/verifydom")
```

Use a subject-restricted internal CA policy for this local example. Check that the on-demand policy follows it and that a second call adds no duplicate.

```python
reset()
init_path(automation_path)
pcfg([{'subjects': ['*.example.com'], 'issuers': [{'module': 'internal'}]}], automation_path+'/policies')
add_on_demand_tls("http://localhost:5431/verifydom")
pols = gcfg(automation_path+'/policies')
test_eq(pols[1].on_demand, True)
add_on_demand_tls("http://localhost:5431/verifydom")
test_eq(len(gcfg(automation_path+'/policies')), 2)
```

## Wildcard subdomains

A wildcard route groups subdomains under a `*.{domain}` host matcher. Caddy can use one wildcard certificate for these hosts. Each subdomain has a route inside the wildcard's `subroute` handler.

Create the wildcard with [`add_wildcard_route`](core.md#add_wildcard_route), then add subdomains with [`add_sub_reverse_proxy`](core.md#add_sub_reverse_proxy) or custom routes with [`add_sub_route`](core.md#add_sub_route). Calling [`add_wildcard_route`](core.md#add_wildcard_route) again leaves the route and its subroutes unchanged.

[source](https://github.com/AnswerDotAI/fastcaddy/blob/main/fastcaddy/core.py#L318)

### add\_wildcard\_route

```python
def add_wildcard_route(
    domain
):
```

*Add a route matching `*.{domain}` (tagged `wildcard-{domain}`) for subroutes; no-op if it already exists*

```python
reset()
setup_caddy(local=True)
add_wildcard_route('something.example.com')
add_wildcard_route('something.example.com')
test_eq(sum(1 for o in gcfg(rts_path) if o['@id']=='wildcard-something.example.com'), 1)
```

[`add_sub_route`](core.md#add_sub_route) appends a route inside the wildcard, replacing any existing route with its `@id`. Use it to configure custom handlers. Our production configuration combines `encode`, a custom router and `reverse_proxy` in one route.

[source](https://github.com/AnswerDotAI/fastcaddy/blob/main/fastcaddy/core.py#L333)

### add\_sub\_route

```python
def add_sub_route(
    domain, route
):
```

*Append `route` to `domain`'s wildcard subroute list, replacing any existing route with the same `@id` in place*

[source](https://github.com/AnswerDotAI/fastcaddy/blob/main/fastcaddy/core.py#L345)

### add\_sub\_reverse\_proxy

```python
def add_sub_reverse_proxy(
    domain, # Domain with an existing wildcard route
    subdomain, # Subdomain to proxy (tagged `{subdomain}.{domain}`)
    port:Union[str, int, Sequence], # A single port or list of ports
    host:str='localhost', # Host the upstream(s) listen on
    st_delay:str='1m', # Keep streaming connections open this long across config reloads (None to disable)
    encode:bool=True, # Compress responses?
):
```

*Create (or replace) a reverse proxy to `{subdomain}.{domain}` inside `domain`'s wildcard route*

```python
add_sub_reverse_proxy('something.example.com', 'foo', 5001)
gid('foo.something.example.com')
```

```python
{ '@id': 'foo.something.example.com',
  'handle': [{'encodings': {'gzip': {'level': 1}, 'zstd': {'level': 'fastest'}}, 'handler': 'encode', 'prefer': ['zstd', 'gzip']}, {'handler': 'reverse_proxy', 'stream_close_delay': '1m', 'upstreams': [{'dial': 'localhost:5001'}]}],
  'match': [{'host': ['foo.something.example.com']}]}
```

Replace the subdomain's route with two upstream ports, then remove it with [`del_id`](core.md#del_id).

```python
add_sub_reverse_proxy('something.example.com', 'foo', [5002, 5003])
subs = gid('wildcard-something.example.com').handle[0].routes
test_eq(len(subs), 1)
test_eq([u.dial for u in subs[0].handle[1].upstreams], ['localhost:5002', 'localhost:5003'])
```

```python
del_id('foo.something.example.com')
test_eq(has_id('foo.something.example.com'), False)
```
