or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/pypi-grpcio

HTTP/2-based RPC framework with synchronous and asynchronous APIs for building distributed systems

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/grpcio@1.74.x

To install, run

npx @tessl/cli install tessl/pypi-grpcio@1.74.0

0

# gRPC Python (grpcio)

1

2

A modern, high-performance RPC framework that uses HTTP/2 for transport and Protocol Buffers as the interface description language. gRPC enables efficient communication between client and server applications across different platforms and languages, with features including streaming, flow control, cancellation, timeouts, authentication, and load balancing.

3

4

## Package Information

5

6

- **Package Name**: grpcio

7

- **Language**: Python

8

- **Installation**: `pip install grpcio`

9

10

## Core Imports

11

12

```python

13

import grpc

14

```

15

16

For async functionality:

17

18

```python

19

import grpc.aio

20

```

21

22

For experimental features:

23

24

```python

25

import grpc.experimental

26

```

27

28

## Basic Usage

29

30

### Simple Client

31

32

```python

33

import grpc

34

import my_service_pb2

35

import my_service_pb2_grpc

36

37

# Create channel

38

channel = grpc.insecure_channel('localhost:50051')

39

40

# Create stub

41

stub = my_service_pb2_grpc.MyServiceStub(channel)

42

43

# Make call

44

request = my_service_pb2.MyRequest(message="Hello")

45

response = stub.MyMethod(request)

46

print(response.reply)

47

48

# Clean up

49

channel.close()

50

```

51

52

### Simple Server

53

54

```python

55

import grpc

56

from concurrent import futures

57

import my_service_pb2_grpc

58

59

class MyServiceServicer(my_service_pb2_grpc.MyServiceServicer):

60

def MyMethod(self, request, context):

61

return my_service_pb2.MyResponse(reply=f"Echo: {request.message}")

62

63

# Create server

64

server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))

65

my_service_pb2_grpc.add_MyServiceServicer_to_server(MyServiceServicer(), server)

66

67

# Add port and start

68

server.add_insecure_port('[::]:50051')

69

server.start()

70

print("Server started on port 50051")

71

server.wait_for_termination()

72

```

73

74

### Async Client/Server

75

76

```python

77

import grpc.aio

78

79

# Async client

80

async def run_client():

81

async with grpc.aio.insecure_channel('localhost:50051') as channel:

82

stub = my_service_pb2_grpc.MyServiceStub(channel)

83

response = await stub.MyMethod(my_service_pb2.MyRequest(message="Hello"))

84

print(response.reply)

85

86

# Async server

87

async def serve():

88

server = grpc.aio.server()

89

my_service_pb2_grpc.add_MyServiceServicer_to_server(MyServiceServicer(), server)

90

listen_addr = '[::]:50051'

91

server.add_insecure_port(listen_addr)

92

await server.start()

93

await server.wait_for_termination()

94

```

95

96

## Architecture

97

98

gRPC Python is built around several key components:

99

100

- **Channels**: Client-side connection management with connectivity monitoring and load balancing

101

- **Stubs**: Client-side objects for making RPC calls, supporting all four RPC patterns

102

- **Servers**: Multi-threaded or async servers with configurable thread pools and interceptors

103

- **Servicers**: Server-side service implementations with full context access

104

- **Interceptors**: Middleware for both client and server sides with state passing via contextvars

105

- **Credentials**: Comprehensive security with SSL/TLS, ALTS, OAuth2, and custom authentication

106

- **Metadata**: Key-value pairs for request/response headers with full lifecycle management

107

108

The framework supports four RPC patterns: unary-unary (single request/response), unary-stream (single request/multiple responses), stream-unary (multiple requests/single response), and stream-stream (bidirectional streaming), all available in both synchronous and asynchronous modes.

109

110

## Capabilities

111

112

### Channel Management

113

114

Client-side channel creation and management with support for secure and insecure connections, connectivity monitoring, interceptor chains, and configurable options for load balancing and connection parameters.

115

116

```python { .api }

117

def insecure_channel(target: str, options=None, compression=None) -> Channel: ...

118

def secure_channel(target: str, credentials: ChannelCredentials, options=None, compression=None) -> Channel: ...

119

def intercept_channel(channel: Channel, *interceptors) -> Channel: ...

120

def channel_ready_future(channel: Channel) -> Future: ...

121

```

122

123

[Channel Management](./channel-management.md)

124

125

### Server Implementation

126

127

Server creation and lifecycle management with support for multiple service registration, port configuration, graceful shutdown, and both synchronous and asynchronous execution models.

128

129

```python { .api }

130

def server(thread_pool, handlers=None, interceptors=None, options=None, maximum_concurrent_rpcs=None, compression=None, xds=False) -> Server: ...

131

132

class Server(abc.ABC):

133

def add_generic_rpc_handlers(self, generic_rpc_handlers): ...

134

def add_insecure_port(self, address: str) -> int: ...

135

def add_secure_port(self, address: str, server_credentials: ServerCredentials) -> int: ...

136

def start(self): ...

137

def stop(self, grace): ...

138

```

139

140

[Server Implementation](./server-implementation.md)

141

142

### Security and Authentication

143

144

Comprehensive security framework with SSL/TLS credentials, mutual authentication, OAuth2 integration, ALTS for GCP environments, and custom authentication plugins.

145

146

```python { .api }

147

def ssl_channel_credentials(root_certificates=None, private_key=None, certificate_chain=None) -> ChannelCredentials: ...

148

def ssl_server_credentials(private_key_certificate_chain_pairs, root_certificates=None, require_client_auth=False) -> ServerCredentials: ...

149

def metadata_call_credentials(metadata_plugin: AuthMetadataPlugin, name=None) -> CallCredentials: ...

150

def access_token_call_credentials(access_token: str) -> CallCredentials: ...

151

def composite_channel_credentials(channel_credentials: ChannelCredentials, *call_credentials) -> ChannelCredentials: ...

152

```

153

154

[Security and Authentication](./security-authentication.md)

155

156

### RPC Patterns and Multi-Callables

157

158

Support for all four RPC patterns with both synchronous and asynchronous invocation methods, including timeout handling, metadata passing, and credential specification.

159

160

```python { .api }

161

class UnaryUnaryMultiCallable(abc.ABC):

162

def __call__(self, request, timeout=None, metadata=None, credentials=None, wait_for_ready=None, compression=None): ...

163

def with_call(self, request, timeout=None, metadata=None, credentials=None, wait_for_ready=None, compression=None): ...

164

def future(self, request, timeout=None, metadata=None, credentials=None, wait_for_ready=None, compression=None): ...

165

166

class UnaryStreamMultiCallable(abc.ABC):

167

def __call__(self, request, timeout=None, metadata=None, credentials=None, wait_for_ready=None, compression=None): ...

168

```

169

170

[RPC Patterns](./rpc-patterns.md)

171

172

### Interceptors

173

174

Client and server-side middleware for cross-cutting concerns like logging, metrics, authentication, and request/response modification, with full support for all RPC patterns.

175

176

```python { .api }

177

class UnaryUnaryClientInterceptor(abc.ABC):

178

def intercept_unary_unary(self, continuation, client_call_details, request): ...

179

180

class ServerInterceptor(abc.ABC):

181

def intercept_service(self, continuation, handler_call_details): ...

182

```

183

184

[Interceptors](./interceptors.md)

185

186

### Async API

187

188

Complete asynchronous API for high-performance async/await programming with native Python asyncio integration, supporting all RPC patterns and server/client implementations.

189

190

```python { .api }

191

# grpc.aio module

192

def insecure_channel(target: str, options=None, compression=None) -> aio.Channel: ...

193

def server(migration_thread_pool=None, handlers=None, interceptors=None, options=None, maximum_concurrent_rpcs=None, compression=None) -> aio.Server: ...

194

195

class Channel(abc.ABC):

196

async def __aenter__(self) -> Channel: ...

197

async def __aexit__(self, exc_type, exc_val, exc_tb): ...

198

def unary_unary(self, method, request_serializer=None, response_deserializer=None) -> UnaryUnaryMultiCallable: ...

199

```

200

201

[Async API](./async-api.md)

202

203

### Error Handling and Status

204

205

Comprehensive error handling with gRPC status codes, custom exceptions, detailed error information, and proper exception propagation for both sync and async contexts.

206

207

```python { .api }

208

class StatusCode(enum.Enum):

209

OK = ...

210

CANCELLED = ...

211

UNKNOWN = ...

212

INVALID_ARGUMENT = ...

213

DEADLINE_EXCEEDED = ...

214

NOT_FOUND = ...

215

ALREADY_EXISTS = ...

216

PERMISSION_DENIED = ...

217

RESOURCE_EXHAUSTED = ...

218

FAILED_PRECONDITION = ...

219

ABORTED = ...

220

OUT_OF_RANGE = ...

221

UNIMPLEMENTED = ...

222

INTERNAL = ...

223

UNAVAILABLE = ...

224

DATA_LOSS = ...

225

UNAUTHENTICATED = ...

226

227

class RpcError(Exception): ...

228

229

class ServicerContext(abc.ABC):

230

def abort(self, code: StatusCode, details: str): ...

231

def abort_with_status(self, status): ...

232

def set_code(self, code: StatusCode): ...

233

def set_details(self, details: str): ...

234

```

235

236

[Error Handling](./error-handling.md)

237

238

### Protocol Buffers Integration

239

240

Runtime loading and compilation of Protocol Buffer definitions from .proto files, enabling dynamic service discovery and client generation without pre-compilation.

241

242

```python { .api }

243

def protos(protobuf_path: str): ...

244

def services(protobuf_path: str): ...

245

def protos_and_services(protobuf_path: str): ...

246

```

247

248

[Protocol Buffers Integration](./protobuf-integration.md)

249

250

### Experimental APIs

251

252

Experimental features in the `grpc.experimental` module providing additional functionality and simplified RPC calling patterns.

253

254

```python { .api }

255

# grpc.experimental module

256

class ChannelOptions:

257

SingleThreadedUnaryStream = ... # Perform unary-stream RPCs on single thread

258

259

def insecure_channel_credentials() -> ChannelCredentials: ...

260

def experimental_api(f): ...

261

def wrap_server_method_handler(wrapper, handler): ...

262

263

# Simple stub functions (available in Python 3.7+)

264

def unary_unary(

265

request,

266

target: str,

267

method: str,

268

request_serializer=None,

269

response_deserializer=None,

270

options=(),

271

channel_credentials=None,

272

insecure: bool = False,

273

call_credentials=None,

274

compression=None,

275

wait_for_ready=None,

276

timeout=None,

277

metadata=None

278

): ...

279

280

def unary_stream(

281

request,

282

target: str,

283

method: str,

284

request_serializer=None,

285

response_deserializer=None,

286

options=(),

287

channel_credentials=None,

288

insecure: bool = False,

289

call_credentials=None,

290

compression=None,

291

wait_for_ready=None,

292

timeout=None,

293

metadata=None

294

): ...

295

296

def stream_unary(

297

request_iterator,

298

target: str,

299

method: str,

300

request_serializer=None,

301

response_deserializer=None,

302

options=(),

303

channel_credentials=None,

304

insecure: bool = False,

305

call_credentials=None,

306

compression=None,

307

wait_for_ready=None,

308

timeout=None,

309

metadata=None

310

): ...

311

312

def stream_stream(

313

request_iterator,

314

target: str,

315

method: str,

316

request_serializer=None,

317

response_deserializer=None,

318

options=(),

319

channel_credentials=None,

320

insecure: bool = False,

321

call_credentials=None,

322

compression=None,

323

wait_for_ready=None,

324

timeout=None,

325

metadata=None

326

): ...

327

328

class UsageError(Exception): ...

329

class ExperimentalApiWarning(Warning): ...

330

```

331

332

## Version Information

333

334

```python { .api }

335

import grpc

336

print(grpc.__version__) # Package version string

337

```

338

339

## Types

340

341

### Core Types

342

343

```python { .api }

344

class ChannelCredentials:

345

def __init__(self, credentials): ...

346

347

class CallCredentials:

348

def __init__(self, credentials): ...

349

350

class ServerCredentials:

351

def __init__(self, credentials): ...

352

353

class Future(abc.ABC):

354

def cancel(self) -> bool: ...

355

def cancelled(self) -> bool: ...

356

def running(self) -> bool: ...

357

def done(self) -> bool: ...

358

def result(self, timeout=None): ...

359

def exception(self, timeout=None): ...

360

def traceback(self, timeout=None): ...

361

def add_done_callback(self, fn): ...

362

363

class ChannelConnectivity(enum.Enum):

364

IDLE = ...

365

CONNECTING = ...

366

READY = ...

367

TRANSIENT_FAILURE = ...

368

SHUTDOWN = ...

369

370

class Compression(enum.IntEnum):

371

NoCompression = ...

372

Deflate = ...

373

Gzip = ...

374

375

class LocalConnectionType(enum.Enum):

376

UDS = ...

377

LOCAL_TCP = ...

378

```