Skip to main content

consulwire

A Python client for the Consul agent, and integrations that register Flask and FastAPI applications in it. It ships a synchronous and an asynchronous client with the same API, fully typed.

Installation

pip install consulwire

# with the integration of your framework
pip install "consulwire[flask]"
pip install "consulwire[fastapi]"

Python 3.10 or newer is required. The client only depends on httpx.

Client

Configuration

from consulwire import Consul

# the agent is found in the environment, http://localhost:8500 otherwise
with Consul() as consul:
    ...
# given explicitly
consul = Consul("http://consul:8500", token="a0b1c2d3e4f5g6h7i8j9", timeout=5.0)

The environment variables of the official tools are read first, then the ones of Spring Cloud Consul, so a Python service is configured like its Java neighbors:

Variable Meaning
CONSUL_HTTP_ADDR Agent address, like consul:8500 or https://consul:8501.
CONSUL_HTTP_SSL true to use https when CONSUL_HTTP_ADDR has no scheme.
CONSUL_HTTP_TOKEN ACL token, only needed when the agent enforces ACLs.
CONSUL_HOST Agent host, when CONSUL_HTTP_ADDR is not set.
CONSUL_PORT Agent port with CONSUL_HOST, 8500 by default.

Usage

The client is organized like the agent HTTP API: each section of the API is an attribute of the client, such as consul.agent.

Register a Service

consul.agent.register_service("my-service", address="my-service", port=8000)
# every option
consul.agent.register_service(
    "my-service",
    address="10.0.0.5",
    port=8000,
    service_id="my-service-1",
    tags=["internal"],
    meta={"version": "1.2.0"},
    checks=[...],
    replace_existing_checks=True,
)

Health Checks

A check is a plain dictionary: nothing to import. Type checkers still verify its keys and values.

from datetime import timedelta

consul.agent.register_service(
    "my-service",
    address="my-service",
    port=8000,
    checks=[
        # healthy while the URL answers a 2xx status
        {"http": "http://my-service:8000/health", "interval": timedelta(seconds=10)},
        # healthy while a TCP connection can be opened
        {"tcp": "my-service:8000", "interval": timedelta(seconds=30)},
    ],
)
Key Checks Meaning
http HTTP URL the agent requests, as reachable from the agent.
tcp TCP host:port the agent connects to, as reachable from the agent.
interval both Time between two checks. Required.
timeout both Time before a check counts as failed, 10 seconds by default.
method HTTP HTTP method, GET by default.
headers HTTP Request headers, such as {"Authorization": "..."}.
tls_skip_verify HTTP Accept any TLS certificate.
deregister_critical_after both Remove the service once the check has been failing this long.
id both Check ID, service:<service id> by default.
name both Check name shown in the Consul UI.

To annotate a variable, the types are in consulwire.agent:

from consulwire.agent import Check, HTTPCheck, TCPCheck

Deregister a Service

consul.agent.deregister_service("my-service")

Asynchronous Client

AsyncConsul has the same API, with coroutines:

from consulwire import AsyncConsul

async with AsyncConsul() as consul:
    await consul.agent.register_service("my-service", address="my-service", port=8000)

Both clients describe their requests with the same code, so they cannot drift apart.

Errors

Every error raised by the package derives from ConsulError:

ConsulError
├── ConfigurationError   an environment variable holds an invalid value (also a ValueError)
├── TransportError       the agent could not be reached: connection refused, timeout, DNS failure
└── HTTPStatusError      the agent answered with an error status (.status_code, .body)
from consulwire import ConsulError, HTTPStatusError

try:
    consul.agent.register_service("my-service", port=8000, checks=[...])
except HTTPStatusError as error:
    # Consul explains its refusals in plain text, like "Invalid check: Interval must be > 0"
    print("Refused: %s" % error.body)
except ConsulError as error:
    print("Consul is unavailable: %s" % error)

Integrations

Each framework has its own module in consulwire.integrations, which needs the matching extra:

Framework Module Extra Entry point
Flask consulwire.integrations.flask consulwire[flask] ConsulExtension
FastAPI, and any Starlette app consulwire.integrations.fastapi consulwire[fastapi] ConsulLifespan

What Every Integration Does

The Address

Other services must reach the application at the registered address. It is chosen in this order:

  1. the address given to the integration;
  2. the host the server listens on, when it names this machine for others (not 0.0.0.0, ::, 127.0.0.1 or localhost);
  3. the local IP address the system uses to reach the agent: the container IP in a Docker network, the LAN IP when the agent is on another machine.

The Health Route

Consul checks the application at health_path, /health by default:

  • when the application already has a GET route there, it is used as it is, so a real check, like a database ping, stays in charge;
  • otherwise, a route answering 200 is added right before the registration, once every route of the application is declared. FastAPI leaves it out of the OpenAPI schema.

The Access Logs

Consul calls the health route every 10 seconds. Those calls are hidden from the access logs of the servers, so the logs keep the real traffic:

Integration Access loggers
Flask werkzeug, gunicorn.access
FastAPI uvicorn.access, gunicorn.access

Only the GET requests of the health route are hidden. log_health_checks=True keeps them.

Deregistration

An application is deregistered only when its framework has a shutdown event:

Integration Deregistered
Flask never: Flask has no shutdown event
FastAPI at the shutdown of the lifespan

An instance that stopped without deregistering, after a crash or a kill -9, is removed by Consul once its health check has been failing for deregister_critical_after, a minute by default, so about a minute and a half with Consul's reaping cycle. Restarting first replaces it: the instance ID is the service name.

When no agent is configured, neither through the consul argument nor the environment, registration is skipped with a log line, and the health route is still added. The same code runs on a laptop without Consul.

Flask

Setup

import flask

from consulwire.integrations.flask import ConsulExtension

application = flask.Flask(__name__)
ConsulExtension(application, name="my-service")


@application.get("/hello")
def hello() -> str:
    return "hello"


application.run(host="0.0.0.0", port=8000)

application.run() registers the application right before it listens, with the port and host it is about to use, read the way Flask reads them: its arguments, then the SERVER_NAME setting, then Flask's default port, 5000.

# with the application factory pattern
consul_extension = ConsulExtension(name="my-service")


def create_application() -> flask.Flask:
    application = flask.Flask(__name__)
    consul_extension.init_app(application)

    return application

The Reloader

With the reloader (debug=True, FLASK_DEBUG=1 or use_reloader=True), Flask starts two processes: one watching the files, and one serving requests, restarted on every change. Only the serving process registers, and each restart replaces the instance.

.env files are loaded before registering, the way application.run() loads them, so CONSUL_HOST and FLASK_DEBUG can come from them.

Other Servers

Servers that do not go through application.run(), like gunicorn or flask run, register the application themselves:

# loaded by every gunicorn worker
consul_extension = ConsulExtension(application, name="my-service")
consul_extension.register(port=int(os.environ["PORT"]))

consul_extension.deregister() is available to a server with a shutdown event of its own, such as gunicorn's on_exit hook.

Options

ConsulExtension(
    application,
    name="my-service",  # name other services look this one up by
    health_path="/health",  # route Consul checks
    address=None,  # see The Address
    consul=None,  # Consul client, from the environment by default
    check_interval=timedelta(seconds=10),  # time between two health checks
    deregister_critical_after=timedelta(minutes=1),  # None keeps dead instances
    tags=(),
    meta=None,
    log_health_checks=False,  # True keeps them in the access logs
)

The extension is stored in application.extensions["consul"], and ConsulExtension.of(application) returns it.

FastAPI

Setup

import uvicorn
from fastapi import FastAPI

from consulwire.integrations.fastapi import ConsulLifespan

application = FastAPI(lifespan=ConsulLifespan(name="my-service", port=8000))


@application.get("/hello")
def hello() -> str:
    return "hello"


uvicorn.run(application, host="0.0.0.0", port=8000)

The lifespan registers the application at startup, before the first request, and deregisters it at shutdown. It uses the asynchronous client, and works with any Starlette application.

With a Lifespan of your Own

FastAPI takes a single lifespan: call the Consul one from yours.

from contextlib import asynccontextmanager

consul_lifespan = ConsulLifespan(name="my-service", port=8000)


@asynccontextmanager
async def lifespan(application: FastAPI):
    database = await connect()

    async with consul_lifespan(application):
        yield

    await database.close()


application = FastAPI(lifespan=lifespan)

Registering last and deregistering first, as above, keeps the instance out of Consul while its dependencies are not ready.

Reload and Workers

  • uvicorn --reload restarts the application on every change: each restart is a shutdown then a startup, so the instance is deregistered then registered again.
  • With several workers (uvicorn --workers 4, or gunicorn with uvicorn workers), every worker registers the same instance, which is harmless, and deregisters it when it stops.

Options

ConsulLifespan(
    name="my-service",  # name other services look this one up by
    port=8000,  # port given to the server
    health_path="/health",  # route Consul checks
    address=None,  # see The Address
    consul=None,  # AsyncConsul client, from the environment by default
    check_interval=timedelta(seconds=10),  # time between two health checks
    deregister_critical_after=timedelta(minutes=1),  # None keeps dead instances
    tags=(),
    meta=None,
    log_health_checks=False,  # True keeps them in the access logs
)

Metadata

Release files for consulwire 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for consulwire 0.1.0
File Size Uploaded Provenance Actions
consulwire-0.1.0.tar.gz 28.0 kB With provenance Details for consulwire-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for consulwire 0.1.0
File Interpreter ABI Platform Actions
consulwire-0.1.0-py3-none-any.whl Python 3 none any Details for consulwire-0.1.0-py3-none-any.whl

Total release size: 53.4 kB

Release files / consulwire-0.1.0.tar.gz

Download URL consulwire-0.1.0.tar.gz
Size 28.0 kB
Tags Source
SHA-256 checksum
How to use checksums
ec1d0900e58d00fa7fbcc71b1600da4cd2fef01d355bfb0f710eb313d56712bf
BLAKE2b-256 checksum
How to use checksums
0e9675ecc32aff6fff5f047bf0275dd6250ddb4696183d171efe858f3ae08bc3
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 9, 2026.

Transparency log

Release files / consulwire-0.1.0-py3-none-any.whl

Download URL consulwire-0.1.0-py3-none-any.whl
Size 25.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
b4aaa75641a4df4a24376be5f0fdc064cfbf2ef58015af39712adcf76bbdc969
BLAKE2b-256 checksum
How to use checksums
e2ac4e7db3a46763acd080590e7034d71df78c3c0c02648c006d466c79219aaf
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 9, 2026.

Transparency log

Security for consulwire 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for consulwire-0.1.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 9, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page