Simple gRPC server based on Python

CK CK 3788 
Created at  
395 0 0

To develop a gRPC server in Python, you first define your service using a Protocol Buffer (.proto) file, then generate Python code from this file using the protoc compiler with the gRPC Python plugin. This generated code provides the necessary structures. Next, you create a class that inherits from the generated service class and implements the methods defined in your .proto file. Finally, you create a gRPC server instance, register your service implementation, and start listening on a specified port, handling incoming client requests.
 

Here’s a step-by-step guide to set up and use gRPC in Python, along with example code:


Step 1: Install the Required Libraries

Install grpcio and grpcio-tools for gRPC support in Python.

pip install grpcio grpcio-tools

Step 2: Define the gRPC Service Using Protocol Buffers

Create a file named example.proto with the following content:

syntax = "proto3";

service ExampleService {
  rpc SayHello (HelloRequest) returns (HelloResponse);
}

message HelloRequest {
  string name = 1;
}

message HelloResponse {
  string message = 1;
}

Step 3: Generate Python Code from the Proto File

Generate the Python gRPC classes from the .proto file:

python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. example.proto

This creates two files:

  • example_pb2.py (message definitions)
  • example_pb2_grpc.py (gRPC service definitions)

Step 4: Implement the gRPC Service

Create a server implementation:

server.py

from concurrent import futures
import grpc
import example_pb2
import example_pb2_grpc

class ExampleServiceServicer(example_pb2_grpc.ExampleServiceServicer):
    def SayHello(self, request, context):
        name = request.name
        return example_pb2.HelloResponse(message=f"Hello, {name}!")

def serve():
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    example_pb2_grpc.add_ExampleServiceServicer_to_server(ExampleServiceServicer(), server)
    server.add_insecure_port("[::]:50051")
    print("Server is running on port 50051")
    server.start()
    server.wait_for_termination()

if __name__ == "__main__":
    serve()

Step 5: Create the gRPC Client

client.py

import grpc
import example_pb2
import example_pb2_grpc

def run():
    with grpc.insecure_channel("localhost:50051") as channel:
        stub = example_pb2_grpc.ExampleServiceStub(channel)
        response = stub.SayHello(example_pb2.HelloRequest(name="World"))
    print(f"Received: {response.message}")

if __name__ == "__main__":
    run()

Step 6: Run the Server and Client

  1. Start the server by running:

    python server.py
    
  2. Run the client in a separate terminal:

    python client.py
    

Output

When you run the client, it will send a request to the server, and the server will respond:

Server:
Server is running on port 50051

Client:
Received: Hello, World!

This is a simple gRPC service setup in Python. You can expand it by adding more methods, using TLS for secure communication, or deploying it in a production environment.

Tags Python gRPC gRPC gRPC Server grpcio grpcio-tools Facebook X
Comments 0
Similar posts
  1. gRPC Server with PHP
    504
  2. gRPC library for Rust
    341
  3. gRPC - Open-source Universal RPC Framework developed by Google
    767
  4. System Requirements and Architecture: Intelligent Priority-Based Scheduler
    166
  1. Milvus and LLM Integration - Very Smart Approach!
    297
  2. Automated API Documentation with PyCharm
    892
  3. How to install python 3.9 alongside python 3.8 on CentOS 7?
    710
  4. How to run Python 3.9 on Mac?
    652
  5. Python Quizs
    501
  6. Automated OpenAPI documentation for a Python Flask API
    1,120
  7. Automated API documentation for a Django REST Framework (DRF) project using drf-yasg (Yet Another Swagger Generator)
    1,029
  8. Uploading a file to a Google Drive Folder programmatically with Python
    3,307
  9. Garbage Collection when your system does not have enough memory in your Python App
    1,011
  10. Method to maximize full CPU performance with Python
    317
  11. How do I get the maximum available of thread in python?
    990
  12. Using Queue Algorithm with Redis - RPUSH and LPOP
    770
  13. Use cache concept with Redis : Let's do Redis programming with Python
    531
  14. Installing Python 3.8 in a venv environment on CentOS 7
    463
  15. CUDA versus OpenCL
    578
  16. Python code to convert PDF file to Excel Spreadsheet
    700
  17. Python script to list files on your Google Drive and download one of them
    941
  18. Coinbase Python API - Basic Example
    462
  19. AWS Lambda Code Example based on Python
    333
  20. Python code using GPU on CentOS with AWS
    1,251
  21. Video Scence Detection with PySceneDetect
    2,320
  22. Python Audio Separation Libraries allowing you to isolate individual tracks
    1,443
  23. Python Version Control for Library Compatibility with pyenv - Downgrading/Upgrading Python Version
    908
  24. Deleting a specific user voice from the original audio track with Python
    548
  25. Creating an MR from the original MP3 audio in Python - Deleting Voice Track from Audio File
    439
  26. Creating mp3 audio file based on the text input with Python
    465
  27. Implementing Text To Speech / Audio with Python3 and pyttsx3
    355
  28. Building Initial Virtual Environment at Python - The first step you should do for Python Programming
    559
  29. Python Simplified Assignment Operators
    533
  30. Trackback module used for Python Threading debugging
    843
Recently updated
  1. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    40
  2. Why SPF and DKIM Are Essential for Linux Email Servers?
    34
  3. How do I create animated background for Google Meet?
    20,611
  4. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    244
  5. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    94
  6. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    157
  7. Array of arguments passed to script in PHP
    90
  8. Invalid Auction Storms in Ad Tech
    98
  9. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    202
  10. The Two Clocks of Ad Server Architecture
    70
  11. Frequency Cap Architecture Overview
    514
  12. Collecting Proof-of-Play from 100,000 Screens
    146
  13. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    287
  14. What is RedisVL?
    109
  15. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    230
  16. TPU & GPU Cluster Management Tools
    243
  17. The Concept of Scaffolding in AI Agents
    233
  18. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    583
  19. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    258
  20. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    339
  21. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    202
  22. Machine Learning: Training vs. Ranking
    221
  23. The Continuous Learning Machine: Designing a Loop That Actually Turns
    222
  24. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    195
  25. Designing a Data Curation System Around a Vector Database
    220
  26. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    256
  27. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    656
  28. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    195
  29. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    217
  30. Understanding Data Lineage
    260