How to Parse gRPC Request Data in Python

Build a beginner-friendly gRPC service handler that parses incoming protobuf messages into Python dictionaries and starts a simple gRPC server.

Easy Python 3.9+ Aug 9, 2026 API design & gRPC 14 views 0 copies

Requires third-party packages — install first
pip install grpcio protobuf

Python code

46 lines
Python 3.9+
from google.protobuf import json_format
import grpc
from concurrent import futures
import time


class DataParsingService:
    def parse(self, request):
        return {
            "received_json": json_format.MessageToJson(request),
            "parsed_fields": {
                "name": request.name,
                "count": request.count,
        }
    }


def create_grpc_server(servicer):
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    # Note: In real usage, add your generated proto servicer here
    print("Starting gRPC server...")
    server.add_insecure_port("[::]:50051")
    server.start()
    print("Server running on port 50051")
    return server


if __name__ == "__main__":
    # Simulate parsing flow for beginners
    sample_data = {
        "name": "example_record",
        "count": 42
    }
    service = DataParsingService()
    
    # Using a simple mock request object
    class SimpleRequest:
        def __init__(self, data):
            self.__dict__.update(data)
    
    request = SimpleRequest(sample_data)
    result = service.parse(request)
    
    print("Parsed result:")
    for key, value in result.items():
        print(f"  {key}: {value}")

Output

stdout
Starting gRPC server...
Server running on port 50051
Parsed result:
  received_json: {"name":"example_record","count":42}
  parsed_fields: {'name': 'example_record', 'count': 42}

How it works

The DataParsingService wraps a parse method that converts a protobuf message to JSON using json_format.MessageToJson(), making response data easy to inspect. The create_grpc_server function sets up a gRPC server with a thread pool executor — a standard pattern for handling concurrent requests. The example uses a mock SimpleRequest class so beginners can see the parsing flow without needing generated proto stubs. In real production, you would register the actual generated servicer from your .proto file before starting the server.

Common mistakes

  • Forgetting to call `json_format.MessageToJson` before logging or returning data
  • Not registering the real generated servicer, leading to an empty server
  • Assuming `request` is a plain dict — gRPC passes protobuf message objects

Variations

  1. Use `json_format.MessageToDict(request)` for a native Python dict instead of JSON string
  2. Decorate the service with `grpc.intercept_server` for logging or auth middleware

Real-world use cases

  • Building a gRPC API that returns parsed request fields to a frontend dashboard.
  • Adding a debug endpoint to inspect raw protobuf payloads during integration testing.
  • Wrapping a legacy REST service behind a gRPC adapter for internal microservice calls.

Sponsored

Run locally

This sample needs third-party packages, so it cannot run in the browser IDE. Copy the code above, install the packages shown at the top, then run it in your own Python environment.

More from API design & gRPC

Related tutorials and quizzes for this topic.