Skip to content

API Reference

connectrpc.client

The Connect client implementations.

ConnectClient

An asynchronous client for the Connect protocol.

When providing an HTTP client, for example to configure TLS settings, it is the caller's responsibility to close it.

Examples:

from pyqwest import Client
from my_service import MyServiceClient

async with (
    Client() as http_client,
    MyServiceClient("http://localhost:8000", http_client=http_client) as client,
):
    # Use the client!

Parameters:

Name Type Description Default
address str

The address of the server to connect to, including scheme.

required
codec Codec | None

The Codec to use for requests. If unset, defaults to binary protobuf. For JSON encoding, use proto_json_codec.

None
protocol ProtocolType

The ProtocolType to use for requests.

CONNECT
accept_compression Iterable[Compression] | None

Compression algorithms to accept from the server. If unset, defaults to gzip. If set to empty, disables response compression.

None
send_compression Compression | None

Compression algorithm to use for sending requests. If unset, defaults to gzip. If set to None, disables request compression.

_gzip
timeout_ms int | None

The timeout for requests in milliseconds.

None
read_max_bytes int | None

The maximum number of bytes to read from the response.

None
interceptors Iterable[Interceptor]

A list of interceptors to apply to requests.

()
http_client Client | None

A pyqwest Client to use for requests.

None

close async

Close the client. After closing, the client cannot be used to make requests.

ConnectClientSync

A synchronous client for the Connect protocol.

When providing an HTTP client, for example to configure TLS settings, it is the caller's responsibility to close it.

Examples:

from pyqwest import SyncClient
from my_service import MyServiceClientSync

with (
    SyncClient() as http_client,
    MyServiceClientSync("http://localhost:8000", http_client=http_client) as client,
):
    # Use the client!

Parameters:

Name Type Description Default
address str

The address of the server to connect to, including scheme.

required
codec Codec | None

The Codec to use for requests. If unset, defaults to binary protobuf. For JSON encoding, use proto_json_codec.

None
protocol ProtocolType

The ProtocolType to use for requests.

CONNECT
accept_compression Iterable[Compression] | None

Compression algorithms to accept from the server. If unset, defaults to gzip. If set to empty, disables response compression.

None
send_compression Compression | None

Compression algorithm to use for sending requests. If unset, defaults to gzip. If set to None, disables request compression.

_gzip
timeout_ms int | None

The timeout for requests in milliseconds.

None
read_max_bytes int | None

The maximum number of bytes to read from the response.

None
interceptors Iterable[InterceptorSync]

A list of interceptors to apply to requests.

()
http_client SyncClient | None

A pyqwest SyncClient to use for requests.

None

close

Close the client. After closing, the client cannot be used to make requests.

ResponseMetadata

Response metadata separate from the message payload.

Commonly, RPC client invocations only need the message payload and do not need to directly read other data such as headers or trailers. In cases where they are needed, initialize this class in a context manager to access the response HTTP status, headers and trailers for the invocation made within the context.

Example
with ResponseMetadata() as resp_data:
    resp = client.MakeHat(Size(inches=10))
    do_something_with_response_payload(resp)
    check_response_headers(resp_data.headers())
    check_response_trailers(resp_data.trailers())

http_status property

Returns the HTTP status code of the response.

If an HTTP response wasn't received, for example due to a network error, this will return None.

headers property

Returns the response headers.

trailers property

Returns the response trailers.

connectrpc.server

The Connect server implementations.

DEFAULT_READ_MAX_BYTES = 1024 * 1024 * 4 module-attribute

The default maximum size of a request message (4MB).

ConnectASGIApplication

ConnectASGIApplication
ConnectASGIApplication

Bases: ABC, Generic[_SVC]

An ASGI application for the Connect protocol.

Parameters:

Name Type Description Default
service _SVC | AsyncGenerator[_SVC]

The service instance or async generator that yields the service during lifespan.

required
desc DescService | None

The descriptor of the service. Method implementations are looked up on the service instance by name using the same conventions as generated code.

None
endpoints Callable[[_SVC], Mapping[str, Endpoint]] | None

Deprecated, pass desc instead. A callable that takes the service instance and returns a mapping of URL paths to endpoints.

None
interceptors Iterable[Interceptor]

A sequence of interceptors to apply to the endpoints.

()
read_max_bytes int | None

Maximum size of request messages.

DEFAULT_READ_MAX_BYTES
compressions Iterable[Compression] | None

Supported compression algorithms. If unset, defaults to gzip. If set to empty, disables compression.

None
codecs Iterable[Codec] | None

The codecs supported by the server. If unset, defaults to Protocol Buffers binary and JSON codecs.

None

path property

Returns the URL path to mount the application to when serving multiple applications.

Endpoint dataclass

Bases: Generic[REQ, RES]

Represents an endpoint in a service.

Attributes:

Name Type Description
method MethodInfo[REQ, RES]

The method to map to the RPC function.

EndpointSync dataclass

Bases: Generic[REQ, RES]

Represents a sync endpoint in a service.

Attributes:

Name Type Description
method MethodInfo[REQ, RES]

The method to map to the RPC function.

ConnectWSGIApplication

ConnectWSGIApplication
ConnectWSGIApplication

Bases: ABC, Generic[_SVC]

A WSGI application for the Connect protocol.

Parameters:

Name Type Description Default
service _SVC | None

The service instance.

None
desc DescService | None

The descriptor of the service. Method implementations are looked up on the service instance by name using the same conventions as generated code.

None
endpoints Mapping[str, EndpointSync] | None

Deprecated, pass service and desc instead. A mapping of URL paths to endpoints.

None
interceptors Iterable[InterceptorSync]

A sequence of interceptors to apply to the endpoints.

()
read_max_bytes int | None

Maximum size of request messages.

DEFAULT_READ_MAX_BYTES
compressions Iterable[Compression] | None

Supported compression algorithms. If unset, defaults to gzip. If set to empty, disables compression.

None
codecs Iterable[Codec] | None

The codecs supported by the server. If unset, defaults to Protocol Buffers binary and JSON codecs.

None

path property

Returns the URL path to mount the application to when serving multiple applications.

connectrpc.code

The Connect error codes.

Code

Bases: Enum

Enumeration of Connect error codes.

CANCELED = 'canceled' class-attribute instance-attribute

RPC canceled, usually by the caller.

UNKNOWN = 'unknown' class-attribute instance-attribute

Catch-all for errors of unclear origin and errors without a more appropriate code.

INVALID_ARGUMENT = 'invalid_argument' class-attribute instance-attribute

Request is invalid, regardless of system state.

DEADLINE_EXCEEDED = 'deadline_exceeded' class-attribute instance-attribute

Deadline expired before RPC could complete or before the client received the response.

NOT_FOUND = 'not_found' class-attribute instance-attribute

User requested a resource (for example, a file or directory) that can't be found.

ALREADY_EXISTS = 'already_exists' class-attribute instance-attribute

Caller attempted to create a resource that already exists.

PERMISSION_DENIED = 'permission_denied' class-attribute instance-attribute

Caller isn't authorized to perform the operation.

RESOURCE_EXHAUSTED = 'resource_exhausted' class-attribute instance-attribute

Operation can't be completed because some resource is exhausted. Use unavailable if the server is temporarily overloaded and the caller should retry later.

FAILED_PRECONDITION = 'failed_precondition' class-attribute instance-attribute

Operation can't be completed because the system isn't in the required state.

ABORTED = 'aborted' class-attribute instance-attribute

The operation was aborted, often because of concurrency issues like a database transaction abort.

OUT_OF_RANGE = 'out_of_range' class-attribute instance-attribute

The operation was attempted past the valid range.

UNIMPLEMENTED = 'unimplemented' class-attribute instance-attribute

The operation isn't implemented, supported, or enabled.

INTERNAL = 'internal' class-attribute instance-attribute

An invariant expected by the underlying system has been broken. Reserved for serious errors.

UNAVAILABLE = 'unavailable' class-attribute instance-attribute

The service is currently unavailable, usually transiently. Clients should back off and retry idempotent operations.

DATA_LOSS = 'data_loss' class-attribute instance-attribute

Unrecoverable data loss or corruption.

UNAUTHENTICATED = 'unauthenticated' class-attribute instance-attribute

Caller doesn't have valid authentication credentials for the operation.

connectrpc.errors

The Connect error types.

ErrorDetail

A self-describing Protobuf message attached to a ConnectError.

Error details are sent over the network to clients, which can then work with strongly-typed data rather than trying to parse a complex error message. For example, you might use details to send a localized error message or retry parameters to a client.

If the message is an Any, it is used directly. Otherwise, the message is packed into an Any, with it also stored to be recoverable from value().

type_name property

The fully-qualified name of the details Protobuf message (for example, acme.foo.v1.FooDetail).

message_bytes property

The Protobuf message serialized as bytes.

value

value
value
value
value

Get the details message as a Protobuf message, or None if it cannot be deserialized.

ConnectError

Bases: Exception

An exception in a Connect RPC.

If a server raises a ConnectError, the same exception content will be raised on the client as well. Errors surfacing on the client side such as timeouts will also be raised as a ConnectError with an appropriate Code.

Parameters:

Name Type Description Default
code Code

The error code.

required
message str

The error message.

required
details Iterable[Message | ErrorDetail]

Additional details about the error.

()

code property

The Connect error code.

message property

The Connect error message.

details property

Additional details about the error, if any.

connectrpc.method

The Connect method information.

IdempotencyLevel

Bases: Enum

The level of idempotency of an RPC method.

This value can affect RPC behaviors, such as determining whether it is safe to retry a request, or what kinds of request modalities are allowed for a given procedure.

UNKNOWN = enum.auto() class-attribute instance-attribute

The default idempotency level.

A method with this idempotency level may not be idempotent. This is appropriate for any kind of method.

NO_SIDE_EFFECTS = enum.auto() class-attribute instance-attribute

The idempotency level that specifies that a given call has no side-effects.

This is equivalent to RFC 9110 § 9.2.1 "safe" methods in terms of semantics. This procedure should not mutate any state. This idempotency level is appropriate for queries, or anything that would be suitable for an HTTP GET request. In addition, due to the lack of side-effects, such a procedure would be suitable to retry and expect that the results will not be altered by preceding attempts.

IDEMPOTENT = enum.auto() class-attribute instance-attribute

The idempotency level that specifies that a given call is "idempotent", such that multiple instances of the same request to this procedure would have the same side-effects as a single request.

This is equivalent to RFC 9110 § 9.2.2 "idempotent" methods. This level is a subset of the previous level. This idempotency level is appropriate for any procedure that is safe to retry multiple times and be guaranteed that the response and side-effects will not be altered as a result of multiple attempts, for example, entity deletion requests.

StreamType

Bases: Enum

The directionality of an RPC method.

UNARY = enum.auto() class-attribute instance-attribute

An RPC with one request and one response.

CLIENT_STREAM = enum.auto() class-attribute instance-attribute

A client-streaming RPC.

SERVER_STREAM = enum.auto() class-attribute instance-attribute

A server-streaming RPC.

BIDI_STREAM = enum.auto() class-attribute instance-attribute

A bidirectional-streaming RPC.

MethodInfo dataclass

Bases: Generic[REQ, RES]

Information about a RPC method within a service.

name instance-attribute

The name of the method within the service.

service_name instance-attribute

The fully qualified service name containing the method.

input instance-attribute

The input message type of the method.

output instance-attribute

The output message type of the method.

idempotency_level instance-attribute

The IdempotencyLevel of the method.

stream_type instance-attribute

The StreamType of the method.

connectrpc.request

The HTTP request context for a Connect invocation.

Headers

Bases: MutableMapping[str, str]

Container of HTTP headers.

This class behaves like a dictionary with case-insensitive keys and string values. It additionally can be used to store multiple values for the same key by using the add method, and retrieve a view including duplicates using allitems.

add

Add a header, appending to existing values without overwriting.

To overwrite an existing value, use self[key] = value instead.

clear

Clear all headers.

getall

Get all values for a header key, including duplicates.

allitems

Return an iterable view of all header items, including duplicates.

items

Return an iterable view of the headers, without duplicates.

keys

Return an iterable view of the header keys.

values

Return an iterable view of the header values, without duplicates.

RequestContext

Bases: Generic[REQ, RES]

Additional context for an RPC request message.

method property

Returns information about the RPC method being invoked.

http_method property

Returns the HTTP method for this request.

This is nearly always POST, but side-effect-free unary RPCs could be made via GET.

request_headers property

Returns the request headers associated with the context.

response_headers property

Returns the response headers that will be sent before the response.

response_trailers property

Returns the response trailers that will be sent after the response.

timeout_ms property

Returns the remaining time until the timeout in milliseconds, or None if no timeout is set.

server_address property

Returns the server address for this request, if available, as a "address:port" string.

  • On the client, this is components from the URL configured when constructing the client.
  • On the server, this is determined from the Host header and scheme of the request.

client_address property

Returns the client address for this request, if available, as a "address:port" string.

  • On the client, this is never populated.
  • On the server, this is the value provided by the server implementation, generally the IP address and ephemeral port of the client.

connectrpc.interceptor

The Connect interceptor protocols.

Interceptor = UnaryInterceptor | ClientStreamInterceptor | ServerStreamInterceptor | BidiStreamInterceptor | MetadataInterceptor[Any] module-attribute

An interceptor to apply to an asynchronous RPC server or client.

InterceptorSync = UnaryInterceptorSync | ClientStreamInterceptorSync | ServerStreamInterceptorSync | BidiStreamInterceptorSync | MetadataInterceptorSync[Any] module-attribute

An interceptor to apply to a synchronous RPC server or client.

BidiStreamInterceptor

Bases: Protocol

An interceptor of an asynchronous bidirectional-streaming RPC method.

intercept_bidi_stream

Intercept a bidirectional-streaming RPC.

Parameters:

Name Type Description Default
call_next Callable[[AsyncIterator[REQ], RequestContext], AsyncIterator[RES]]

A callable to invoke to continue processing, either to another interceptor or the actual RPC. Generally will be called with the same request the interceptor received but the request can be replaced as needed. Can be skipped if returning a response from the interceptor directly.

required
request AsyncIterator[REQ]

The request message iterator.

required
ctx RequestContext

The request context.

required

Returns:

Type Description
AsyncIterator[RES]

The response message iterator.

ClientStreamInterceptor

Bases: Protocol

An interceptor of an asynchronous client-streaming RPC method.

intercept_client_stream async

Intercept a client-streaming RPC.

Parameters:

Name Type Description Default
call_next Callable[[AsyncIterator[REQ], RequestContext], Awaitable[RES]]

A callable to invoke to continue processing, either to another interceptor or the actual RPC. Generally will be called with the same request the interceptor received but the request can be replaced as needed. Can be skipped if returning a response from the interceptor directly.

required
request AsyncIterator[REQ]

The request message iterator.

required
ctx RequestContext

The request context.

required

Returns:

Type Description
RES

The response message.

MetadataInterceptor

Bases: Protocol[T]

An interceptor that can be applied to any type of method.

Only metadata such as headers and trailers is accessible. To access request and response bodies of a method, instead use an interceptor corresponding to the type of method such as UnaryInterceptor.

On servers, metadata interceptors at the front of the interceptor list are invoked before the request message is read or parsed, allowing logic such as authentication to reject a request without processing its body. A metadata interceptor following a message interceptor is invoked in order within the chain, after the request message is parsed.

on_start async

Handle the start of the RPC.

The return value is passed to on_end as-is. For example, if measuring RPC invocation time, on_start may return the current time. If a return value isn't needed or on_end won't be used, return None.

on_end async

Handle the end of the RPC.

ServerStreamInterceptor

Bases: Protocol

An interceptor of an asynchronous server-streaming RPC method.

intercept_server_stream

Intercept a server-streaming RPC.

Parameters:

Name Type Description Default
call_next Callable[[REQ, RequestContext], AsyncIterator[RES]]

A callable to invoke to continue processing, either to another interceptor or the actual RPC. Generally will be called with the same request the interceptor received but the request can be replaced as needed. Can be skipped if returning a response from the interceptor directly.

required
request REQ

The request message.

required
ctx RequestContext

The request context.

required

Returns:

Type Description
AsyncIterator[RES]

The response message iterator.

UnaryInterceptor

Bases: Protocol

An interceptor of an asynchronous unary RPC method.

intercept_unary async

Intercept a unary RPC.

Parameters:

Name Type Description Default
call_next Callable[[REQ, RequestContext], Awaitable[RES]]

A callable to invoke to continue processing, either to another interceptor or the actual RPC. Generally will be called with the same request the interceptor received but the request can be replaced as needed. Can be skipped if returning a response from the interceptor directly.

required
request REQ

The request message.

required
ctx RequestContext

The request context.

required

Returns:

Type Description
RES

The response message.

BidiStreamInterceptorSync

Bases: Protocol

An interceptor of a synchronous bidirectional-streaming RPC method.

intercept_bidi_stream_sync

Intercept a bidirectional-streaming RPC.

Parameters:

Name Type Description Default
call_next Callable[[Iterator[REQ], RequestContext], Iterator[RES]]

A callable to invoke to continue processing, either to another interceptor or the actual RPC. Generally will be called with the same request the interceptor received but the request can be replaced as needed. Can be skipped if returning a response from the interceptor directly.

required
request Iterator[REQ]

The request message iterator.

required
ctx RequestContext

The request context.

required

Returns:

Type Description
Iterator[RES]

The response message iterator.

ClientStreamInterceptorSync

Bases: Protocol

An interceptor of a synchronous client-streaming RPC method.

intercept_client_stream_sync

Intercept a client-streaming RPC.

Parameters:

Name Type Description Default
call_next Callable[[Iterator[REQ], RequestContext], RES]

A callable to invoke to continue processing, either to another interceptor or the actual RPC. Generally will be called with the same request the interceptor received but the request can be replaced as needed. Can be skipped if returning a response from the interceptor directly.

required
request Iterator[REQ]

The request message iterator.

required
ctx RequestContext

The request context.

required

Returns:

Type Description
RES

The response message.

MetadataInterceptorSync

Bases: Protocol[T]

An interceptor that can be applied to any type of method.

Only metadata such as headers and trailers is accessible. To access request and response bodies of a method, instead use an interceptor corresponding to the type of method such as UnaryInterceptorSync.

On servers, metadata interceptors at the front of the interceptor list are invoked before the request message is read or parsed, allowing logic such as authentication to reject a request without processing its body. A metadata interceptor following a message interceptor is invoked in order within the chain, after the request message is parsed.

on_start_sync

Handle the start of the RPC.

The return value is passed to on_end_sync as-is. For example, if measuring RPC invocation time, on_start_sync may return the current time. If a return value isn't needed or on_end_sync won't be used, return None.

on_end_sync

Handle the end of the RPC.

ServerStreamInterceptorSync

Bases: Protocol

An interceptor of a synchronous server-streaming RPC method.

intercept_server_stream_sync

Intercept a server-streaming RPC.

Parameters:

Name Type Description Default
call_next Callable[[REQ, RequestContext], Iterator[RES]]

A callable to invoke to continue processing, either to another interceptor or the actual RPC. Generally will be called with the same request the interceptor received but the request can be replaced as needed. Can be skipped if returning a response from the interceptor directly.

required
request REQ

The request message.

required
ctx RequestContext

The request context.

required

Returns:

Type Description
Iterator[RES]

The response message iterator.

UnaryInterceptorSync

Bases: Protocol

An interceptor of a synchronous unary RPC method.

intercept_unary_sync

Intercept a unary RPC.

Parameters:

Name Type Description Default
call_next Callable[[REQ, RequestContext], RES]

A callable to invoke to continue processing, either to another interceptor or the actual RPC. Generally will be called with the same request the interceptor received but the request can be replaced as needed. Can be skipped if returning a response from the interceptor directly.

required
request REQ

The request message.

required
ctx RequestContext

The request context.

required

Returns:

Type Description
RES

The response message.

connectrpc.codec

The Connect codecs.

Codec

Bases: Protocol[T_contra, U]

name

Return the name of the codec.

This corresponds to the content-type used in requests.

encode

Marshals the given message.

decode

Unmarshals the given message.

proto_binary_codec

Return the Protocol Buffers binary codec.

proto_json_codec

Return the Protocol Buffers JSON codec.

Parameters:

Name Type Description Default
registry Registry | None

An optional protobuf Registry to use for marshaling Any and extensions in messages. If not provided, a default registry containing WKTs will be used.

None
ignore_unknown_fields bool

Whether to ignore unknown fields when decoding JSON messages. If not provided, defaults to True.

True

connectrpc.protocol

The Connect protocol types.

ProtocolType

Bases: Enum

A protocol supported by Connect.

CONNECT = 1 class-attribute instance-attribute

The Connect protocol.

GRPC = 2 class-attribute instance-attribute

The gRPC protocol.

GRPC_WEB = 3 class-attribute instance-attribute

The gRPC-Web protocol.

connectrpc.compression

Protocol for defining compression to use with Connect.

Compression

Bases: Protocol

Protocol for compression methods.

By default, gzip compression is used. Other compression methods can be used by specifying implementations of this protocol. We provide standard implementations for:

name

Return the name of the compression method.

This value is used in HTTP headers to indicate accepted and used compression.

compress

Compress the given data.

decompress

Decompress the given data.

Parameters:

Name Type Description Default
data bytes | bytearray | memoryview

The data to decompress.

required
read_max_bytes int | None

The limit on the number of uncompressed bytes.

None

Raises:

Type Description
ConnectError

(RESOURCE_EXHAUSTED) If the decompressed data exceeds the limit.

Returns:

Type Description
bytes

The decompressed data.

brotli

Brotli compression.

BrotliCompression

Bases: Compression

Compression implementation using Brotli.

Parameters:

Name Type Description Default
quality int

Compression quality to use.

3
name

Return the compression name for Brotli.

compress

Compress the given data using Brotli.

decompress

Decompress the given data using Brotli.

gzip

GZip compression.

GzipCompression

Bases: Compression

Compression implementation using Gzip.

Parameters:

Name Type Description Default
level int

Compression level to use.

6
name

Return the compression name for Gzip.

compress

Compress the given data using Gzip.

decompress

Decompress the given data using Gzip.

zstd

Zstandard compression.

ZstdCompression

Bases: Compression

Compression implementation using Zstandard.

Parameters:

Name Type Description Default
level int

Compression level to use.

3
name

Return the compression name for Zstandard.

compress

Compress the given data using Zstandard.

decompress

Decompress the given data using Zstandard.

connectrpc.compat

Support for the google.protobuf Protobuf implementation with Connect.

google_protobuf_binary_codec

Return the Protocol Buffers binary codec using google.protobuf.

google_protobuf_codecs

Return the codecs for marshaling Protocol Buffers using google.protobuf.

google_protobuf_json_codec

Return the Protocol Buffers JSON codec using google.protobuf.

Parameters:

Name Type Description Default
ignore_unknown_fields bool

Whether to ignore unknown fields when decoding JSON messages. If not provided, defaults to True.

True

connectrpc_grpcreflect

Service implementations for the gRPC reflection service.

ServerReflectionService

Bases: ServerReflection

Asynchronous service implementation for gRPC reflection.

The services in the passed in descriptors will be made available for reflection, along with the v1 and v1alpha reflection services. For DescFile, this means all the services declared in that file. Note that file dependencies are also automatically added and available for resolution by name, but the service list will only reflect the reflection services and the descriptors passed in.

Serve it with ServerReflectionASGIApplication.

Parameters:

Name Type Description Default
*descs DescFile | DescService

The descriptors to make available for reflection.

()

ServerReflectionASGIApplication

Bases: ConnectASGIApplication[ServerReflection]

ServerReflectionServiceSync

Bases: ServerReflectionSync

Synchronous service implementation for gRPC reflection.

The services in the passed in descriptors will be made available for reflection, along with the v1 and v1alpha reflection services. For DescFile, this means all the services declared in that file. Note that file dependencies are also automatically added and available for resolution by name, but the service list will only reflect the reflection services and the descriptors passed in.

Serve it with ServerReflectionWSGIApplication.

Parameters:

Name Type Description Default
*descs DescFile | DescService

The descriptors to make available for reflection.

()

ServerReflectionWSGIApplication

Bases: ConnectWSGIApplication[ServerReflectionSync]

ServerReflectionAlphaService

Bases: ServerReflection

Asynchronous service implementation for gRPC reflection (v1alpha).

The services in the passed in descriptors will be made available for reflection, along with the v1 and v1alpha reflection services. For DescFile, this means all the services declared in that file. Note that file dependencies are also automatically added and available for resolution by name, but the service list will only reflect the reflection services and the descriptors passed in.

Serve it with ServerReflectionAlphaASGIApplication.

Parameters:

Name Type Description Default
*descs DescFile | DescService

The descriptors to make available for reflection.

()

ServerReflectionAlphaASGIApplication

Bases: ConnectASGIApplication[ServerReflection]

ServerReflectionAlphaServiceSync

Bases: ServerReflectionSync

Synchronous service implementation for gRPC reflection (v1alpha).

The services in the passed in descriptors will be made available for reflection, along with the v1 and v1alpha reflection services. For DescFile, this means all the services declared in that file. Note that file dependencies are also automatically added and available for resolution by name, but the service list will only reflect the reflection services and the descriptors passed in.

Serve it with ServerReflectionAlphaWSGIApplication.

Parameters:

Name Type Description Default
*descs DescFile | DescService

The descriptors to make available for reflection.

()

ServerReflectionAlphaWSGIApplication

Bases: ConnectWSGIApplication[ServerReflectionSync]

connectrpc_grpchealth

Service implementations for the gRPC health checking service.

HealthService

Bases: Health

Asynchronous service implementation for gRPC health checking.

Serve it with HealthASGIApplication.

Watch is supported if the checker implements Watcher. Under asyncio, a call to Watch ends as soon as its client disconnects. Under trio, the server notices a disconnect only when the call next sends a status, so the call ends at its deadline or at the next status change of the watched service, whichever comes first.

Parameters:

Name Type Description Default
checker Checker

The checker that reports the status of each service.

required

HealthASGIApplication

Bases: ConnectASGIApplication[Health]

HealthServiceSync

Bases: HealthSync

Synchronous service implementation for gRPC health checking.

Serve it with HealthWSGIApplication.

Watch is supported if the checker implements WatcherSync. Each call to Watch occupies a server thread while it is open. The server notices a disconnect only when the call next sends a status, so a call whose client disconnects ends at its deadline or at the next status change of the watched service, whichever comes first.

Parameters:

Name Type Description Default
checker CheckerSync

The checker that reports the status of each service.

required

HealthWSGIApplication

Bases: ConnectWSGIApplication[HealthSync]

StaticChecker

Bases: Checker, CheckerSync, Watcher, WatcherSync

Health statuses set explicitly for each service.

The checker reports ServingStatus.SERVING for the server as a whole (the empty service name) unless a different status is set for it. Services that have no status set are unknown.

It is safe to call set_status from any thread while requests are being served, including from synchronous code while an asynchronous application serves the checker.

Parameters:

Name Type Description Default
*services str

Fully-qualified protobuf service names, such as "acme.user.v1.UserService".

()

set_status

Set the status of a service, registering it if it is unknown.

Active watches of the service receive the new status.

Parameters:

Name Type Description Default
service str

The fully-qualified protobuf service name, or the empty string for the status of the server as a whole.

required
status ServingStatus

The new status of the service.

required

ServingStatus = HealthCheckResponse.ServingStatus module-attribute

The serving status of a service, as reported by the health service.

Its values are UNKNOWN, SERVING, NOT_SERVING, and SERVICE_UNKNOWN. Checkers report an unknown service as None; Watch sends SERVICE_UNKNOWN for it.

Checker

Bases: Protocol

Reports the health of each service to HealthService.

The methods may be called concurrently. To support Watch, the checker must also implement Watcher.

check async

Return the status of a service, or None if the service is unknown.

Parameters:

Name Type Description Default
service str

The fully-qualified protobuf service name, or the empty string for the status of the server as a whole.

required

list async

Return the status of every known service, keyed by service name.

CheckerSync

Bases: Protocol

Reports the health of each service to HealthServiceSync.

The methods may be called concurrently from any thread. To support Watch, the checker must also implement WatcherSync.

check_sync

Return the status of a service, or None if the service is unknown.

Parameters:

Name Type Description Default
service str

The fully-qualified protobuf service name, or the empty string for the status of the server as a whole.

required

list_sync

Return the status of every known service, keyed by service name.

Watcher

Bases: Protocol

Reports changes in the health of a service to HealthService.

A Checker that also implements Watcher supports the Watch RPC. Otherwise, Watch fails with Code.UNIMPLEMENTED, and gRPC clients that check health with Watch treat the server as healthy.

watch

Yield the status of a service now and again whenever it may have changed.

The status is None while the service is unknown. Watch sends a status only when it differs from the last one sent, so yielding an unchanged status is harmless.

Parameters:

Name Type Description Default
service str

The fully-qualified protobuf service name, or the empty string for the status of the server as a whole.

required

WatcherSync

Bases: Protocol

Reports changes in the health of a service to HealthServiceSync.

A CheckerSync that also implements WatcherSync supports the Watch RPC. Otherwise, Watch fails with Code.UNIMPLEMENTED, and gRPC clients that check health with Watch treat the server as healthy.

watch_sync

Yield the status of a service now and again whenever it may have changed.

The status is None while the service is unknown. Watch sends a status only when it differs from the last one sent, so yielding an unchanged status is harmless.

Parameters:

Name Type Description Default
service str

The fully-qualified protobuf service name, or the empty string for the status of the server as a whole.

required
timeout float | None

Seconds until the call's deadline, or None if it has none. The iterator should end once they pass.

required

connectrpc_otel

OpenTelemetry instrumentation for Connect.

ConnectInstrumentor

Bases: BaseInstrumentor

Instrumentor that adds OpenTelemetry to all Connect clients and servers.

Once instrumented, every client and ASGI or WSGI application created afterwards gets an OpenTelemetryInterceptor as its first interceptor, unless one was passed explicitly. It is registered as an opentelemetry_instrumentor entry point, so opentelemetry-instrument enables it automatically.

instrument() accepts optional tracer_provider and meter_provider keyword arguments, which are passed to each interceptor.

OpenTelemetryInterceptor

Interceptor to generate telemetry for RPC server and client requests.

Parameters:

Name Type Description Default
propagator TextMapPropagator | None

The OpenTelemetry TextMapPropagator to use. If not provided, the global default will be used.

None
tracer_provider TracerProvider | None

The OpenTelemetry TracerProvider to use. If not provided, the global default will be used.

None
meter_provider MeterProvider | None

The OpenTelemetry MeterProvider to use. If not provided, the global default will be used.

None
client bool

Whether this interceptor is for a client or server.

False

connectrpc_fastapi

FastAPI integration for Connect.

ServiceType

Bases: Protocol

A generated service protocol class.

connect_router

Create a FastAPI router serving a Connect service.

Each RPC becomes a route. FastAPI's dependency injection provides the service instance for each request. The RPC runs while the response is sent, after request-scoped dependencies are resolved and before they are cleaned up.

The routes document their request and response messages with placeholder schemas. add_connect_schemas replaces them with the messages' schemas for docs.

Parameters:

Name Type Description Default
service type[_SVC]

The generated service protocol class.

required
get_service Callable[..., _SVC | Awaitable[_SVC] | AsyncIterator[_SVC] | Iterator[_SVC]]

A FastAPI dependency providing the service instance.

required
application Callable[[_SVC], ConnectASGIApplication[_SVC]] | None

Creates the Connect application for a service instance. Defaults to the application class generated next to the service, or a ConnectASGIApplication for the service if there is none. Use this to pass options such as interceptors.

None
tags Sequence[str] | None

OpenAPI tags for the routes. Defaults to the service's type name.

None

Raises:

Type Description
TypeError

If the service is a generated sync service protocol and application is not passed.

add_connect_schemas

Add the schemas of Connect messages to the application's OpenAPI schema.

The routes created by connect_router document their messages with placeholder schemas. This replaces them with references to the messages' schemas, keyed by type name, and adds the schemas. Without it, the OpenAPI schema is valid and documents the messages as objects without fields.

Call it after any other replacement of the application's openapi method. Routers may be included before or after. The schema is returned by the application's openapi method. The application's openapi_schema attribute keeps the placeholders.

Parameters:

Name Type Description Default
app FastAPI

The FastAPI application serving Connect routes.

required

Raises:

Type Description
ValueError

If a schema of a message's type name is already present with different content. Raised by the application's openapi method.