dcarbone / php-consul-api
PHP client for the Consul HTTP API
Requires
- php: ^8.2
- ext-curl: *
- ext-json: *
- brick/math: ^1.0
- dcarbone/gohttp: ^v1.0.0
- dcarbone/gotime: ^v2.0
- guzzlehttp/guzzle: ^7.4
- guzzlehttp/psr7: ^2.4
Requires (Dev)
- phpunit/phpunit: ^11.5 || ^12.0
Suggests
None
Provides
None
Conflicts
None
Replaces
None
- dev-main
- v3.2.0
- v3.1.0
- v3.0.0
- v3.0.0-rc1
- v2.0.2
- v2.0.1
- v2.0.0
- v1.1.7
- v1.1.6
- v1.1.5
- v1.1.4
- v1.1.3
- v1.1.2
- v1.1.1
- v1.1.0
- v1.0.5
- v1.0.4
- v1.0.3
- v1.0.2
- v1.0.1
- v1.0.0
- 0.6.x-dev
- 0.6.4
- 0.6.3
- 0.6.2.1
- 0.6.2
- 0.6.1.1
- 0.6.1
- 0.6.0
- 0.5.2
- 0.5.1
- 0.5.0
- 0.4.5
- 0.4.4.1
- 0.4.4
- 0.4.3
- 0.4.2
- 0.4.1
- 0.4.0
- 0.3.10
- 0.3.9
- 0.3.8
- 0.3.7
- 0.3.6
- 0.3.5
- 0.3.4
- 0.3.3
- 0.3.2
- 0.3.1
- 0.3.0
- 0.2.4
- 0.2.3
- 0.2.2
- 0.2.1
- 0.2.0
- 0.1.0
- dev-dcarbone/config-entry
This package is auto-updated.
Last update: 2026-11-07 01:02:45 UTC
README
A PHP client for the Consul HTTP API, modeled closely on the official Go client.
đŸ“– Full documentation lives in the wiki.
Requirements
- PHP 8.2+ with
ext-json guzzlehttp/guzzle^7.4(default HTTP client; anyGuzzleHttp\ClientInterfaceworks)brick/math^1.0(foruint64values)dcarbone/gotime^v2.0(for Go-style durations)
Installation
composer require dcarbone/php-consul-api:^v3.1
Quick Start
use DCarbone\PHPConsulAPI\Config; use DCarbone\PHPConsulAPI\Consul; use DCarbone\PHPConsulAPI\KV\KVPair; // With no arguments, configuration is read from the standard CONSUL_* environment variables, // falling back to http://localhost:8500. $consul = new Consul(); // ...or configure it explicitly. $consul = new Consul(config: new Config( Address: 'consul.example.com:8500', Token: 'my-acl-token', )); $err = $consul->KV->Put(p: new KVPair(Key: 'app/config/db', Value: 'postgres://localhost'))->Err; if (null !== $err) { throw new \RuntimeException((string)$err); } [$pair, $qm, $err] = $consul->KV->Get(key: 'app/config/db'); if (null !== $err) { throw new \RuntimeException((string)$err); } echo $pair?->Value; // "postgres://localhost" ($pair is null if the key does not exist) echo $qm->LastIndex; // index to use for blocking queries
Configuration
Config mirrors the Go client's api.Config, and new Consul(config: $config) applies the same defaults and
precedence as Go's api.NewClient. Every parameter is optional.
| Parameter | Default / Env var | Description |
|---|---|---|
Address |
CONSUL_HTTP_ADDR, else localhost:8500 |
host:port, http://, https:// or unix:// URL |
Scheme |
CONSUL_HTTP_SSL (true → https), else http |
http or https |
PathPrefix |
'' |
Path prefix for every request (reverse proxies) |
Datacenter |
'' |
Default datacenter for requests |
Namespace |
CONSUL_NAMESPACE |
Default namespace (Consul Enterprise) |
Partition |
CONSUL_PARTITION |
Default admin partition (Consul Enterprise) |
HttpAuth |
CONSUL_HTTP_AUTH |
HTTP basic auth, as user:pass or an HttpAuth |
WaitTime |
none | Default max wait for blocking queries (e.g. '5m') |
Token |
CONSUL_HTTP_TOKEN |
ACL token |
TokenFile |
CONSUL_HTTP_TOKEN_FILE |
File containing the ACL token |
CAFile |
CONSUL_CACERT |
CA certificate used to verify the server |
CAPath |
CONSUL_CAPATH |
Directory of (hashed) CA certificates |
CertFile |
CONSUL_CLIENT_CERT |
Client certificate (requires KeyFile) |
KeyFile |
CONSUL_CLIENT_KEY |
Client key (requires CertFile) |
TLSServerName |
CONSUL_TLS_SERVER_NAME |
SNI server name (stored only, see wiki) |
InsecureSkipVerify |
CONSUL_HTTP_SSL_VERIFY (false → skip), else false |
Disable TLS certificate verification |
HttpClient |
new GuzzleHttp\Client() |
Any GuzzleHttp\ClientInterface |
JSONEncodeOpts |
JSON_UNESCAPED_SLASHES |
Flags passed to json_encode |
JSONDecodeMaxDepth |
512 |
Max depth passed to json_decode |
JSONDecodeOpts |
0 |
Flags passed to json_decode |
Boolean env vars are parsed like Go's strconv.ParseBool (1, t, T, TRUE, true, True and their false
equivalents); empty env vars are treated as unset.
For proxies, custom timeouts, middleware, etc., construct your own Guzzle client and pass it as HttpClient.
See Configuration for address parsing, token
precedence, TLS and other details.
Differences from the Go client
Configuration matches the Go client's api.NewClient() except:
- There is no
Transportor nestedTLSConfig. TLS fields live directly onConfig, and in-memory PEM (CAPem,CertPEM,KeyPEM) is not supported. TLSServerNameis stored but not applied, because Guzzle has no SNI override.- TLS, basic auth and timeout are applied per request, so they also apply to a custom
HttpClient. Go ignoresTLSConfigwhen you supply your own client. unix://addresses requireext-curl, and requests are sent withHost: localhost.
Other differences are covered under Working with Responses, Clients and Models. For the full list, including Go features not yet implemented (Connect, Snapshot, Lock/Semaphore, etc.), see Differences from Go.
Working with Responses
Every API call returns a response object. Responses can be destructured like the multiple return values of the Go client, or used via properties and getters:
// Read endpoints: [value, QueryMeta, error] [$services, $qm, $err] = $consul->Catalog->Services(); // Write endpoints with a value: [value, WriteMeta, error] [$sessionID, $wm, $err] = $consul->Session->Create(sessionEntry: $entry); // Write endpoints without a value: [WriteMeta, error] [$wm, $err] = $consul->KV->Delete(key: 'app/config/db'); // Some endpoints return no metadata: [value, error] [$leader, $err] = $consul->Status->Leader(); // Object form $resp = $consul->KV->Get(key: 'app/config/db'); $resp->getValue(); $resp->getQueryMeta(); $resp->getErr();
A few Agent methods return only null|Error. The exact shape of each method is documented on its client's
wiki page.
Errors are never thrown for transport or API failures. They are returned as DCarbone\PHPConsulAPI\PHPLib\Error
instances, which can be cast to a string.
Query and write options
Each method accepts an optional QueryOptions or WriteOptions argument to override the datacenter, token, consistency
mode, and so on per request. Blocking queries work the same as in Go:
use DCarbone\PHPConsulAPI\QueryOptions; [$pair, $qm, $err] = $consul->KV->Get(key: 'app/config/db'); [$pair, $qm, $err] = $consul->KV->Get( key: 'app/config/db', opts: new QueryOptions(WaitIndex: $qm->LastIndex, WaitTime: '30s'), );
Big Integers (uint64)
As of v3.1.0, every field that Consul defines as uint64 is a Brick\Math\BigInteger.
This covers CreateIndex, ModifyIndex, LockIndex, KVPair::$Flags, QueryMeta::$LastIndex,
QueryOptions::$WaitIndex, Raft indexes and terms, and the return value of EventClient::IDToIndex().
PHP's int is signed, so values above PHP_INT_MAX would otherwise overflow.
- Setting: constructors and setters accept a non-negative
int, a numericstring, or aBigInteger. Strings are validated withBigInteger::parse(). Negative, non-integer, and out-of-range values throw\InvalidArgumentException. - Reading: use the
BigIntegerAPI (isEqualTo(),toInt(),(string)) rather than PHPintoperators. - JSON: responses are decoded with
JSON_BIGINT_AS_STRING. Use\DCarbone\PHPConsulAPI\PHPLib\encode_json()rather thanjson_encode()if you needBigIntegervalues written as JSON numbers.
$pair = new KVPair(Key: 'app/config', Flags: '18446744073709551615'); if ($pair->Flags->isEqualTo(42)) { /* ... */ } $index = (string)$qm->LastIndex;
See Big Integers.
Clients
Each client is available on Consul both as a property ($consul->KV) and as a method ($consul->KV()).
| Client | Consul API | Wiki |
|---|---|---|
ACL |
/v1/acl |
ACL |
Agent |
/v1/agent |
Agent |
Catalog |
/v1/catalog |
Catalog |
ConfigEntry |
/v1/config |
ConfigEntry |
Coordinate |
/v1/coordinate |
Coordinate |
Debug |
/debug/pprof |
Debug |
Event |
/v1/event |
Event |
Health |
/v1/health |
Health |
KV |
/v1/kv |
KV |
Operator |
/v1/operator |
Operator |
Peering |
/v1/peering |
Peering |
PreparedQuery |
/v1/query |
PreparedQuery |
Session |
/v1/session |
Session |
Status |
/v1/status |
Status |
Txn |
/v1/txn |
Txn |
Unlike the Go client, there are no separate *Opts method variants. Each method takes an optional trailing options
argument instead.
Models
Models are plain PHP classes with public properties, getters and setters, and named constructor parameters:
use DCarbone\PHPConsulAPI\Agent\AgentServiceCheck; use DCarbone\PHPConsulAPI\Agent\AgentServiceRegistration; $err = $consul->Agent->ServiceRegister(service: new AgentServiceRegistration( ID: 'web-1', Name: 'web', Tags: ['v1'], Port: 8080, Check: new AgentServiceCheck(TTL: '30s', DeregisterCriticalServiceAfter: '1m'), ));
Duration fields accept Go duration strings ('30s'), integers (nanoseconds), \DateInterval, or
DCarbone\Go\Time\Duration. They are stored as Time\Duration.
Constructing models from an associative array (new KVPair(data: [...])) is deprecated. Use named parameters, or
Model::jsonUnserialize($decoded) to hydrate from decoded JSON.
Version Compatibility
v3.x requires PHP 8.2+.
| PHPConsulAPI | Consul |
|---|---|
| 0.3.x | 0.6.4 |
| 0.6.x | 0.7–0.8 |
| v1.x | 0.9–current |
| v2.x | 0.9–current |
| v3.x | 0.9–current |
| dev-main | current |
The library is tested against the latest Consul release. Newer versions may work with older Consul agents in a limited capacity, but backwards-compatibility issues with older agents will not be addressed.
Upgrading to v3
FakeMap,FakeSlice,ReadableDurationand theTranscodinghelpers have been removed. Map-like fields are now associative arrays.- All models, including
Config, use named constructor parameters. Array construction of models is deprecated, andConfigcan no longer be constructed from an array. - (v3.1.0)
uint64fields areBrick\Math\BigInteger. See Big Integers (uint64). - (v3.1.0)
dcarbone/gotimehas been upgraded tov2. - (next release) TLS certificates are now verified by default,
CAFileis honored, andCONSUL_HTTP_SSL_VERIFY=falsedisables verification, matching the Go client. Previously, verification was disabled unlessInsecureSkipVerifywastrue. - (next release)
HttpAuth/CONSUL_HTTP_AUTHcredentials are now sent as HTTP basic auth on every request. Previously they were parsed but never sent. - (next release)
Confignow follows Go'sapi.NewClientexactly: the default address islocalhost:8500,Addressmay carry ahttp://,https://orunix://scheme and a path prefix,TokenFilefollows Go's token precedence, boolean env vars use GoParseBoolsemantics (yes/no/on/offare no longer accepted), andPartition,PathPrefix,CAPathandTLSServerNamewere added.
See Upgrading for details.
Development
composer install # unit tests only ./vendor/bin/phpunit -c phpunit.xml --testsuite unit # full suite; integration tests start and stop a local `consul` agent automatically, # so the `consul` binary must be on your PATH ./vendor/bin/phpunit -c phpunit.xml # static analysis and refactoring tools are installed separately under tools/ composer install --working-dir tools/rector composer install --working-dir tools/phpstan composer install --working-dir tools/psalm composer rector composer phpstan composer psalm
See Development.