12

I want to know how to send custom header (or metadata) using Python gRPC. I looked into documents and I couldn't find anything.

Daniel Walker
  • 6,380
  • 5
  • 22
  • 45
avi
  • 9,292
  • 11
  • 47
  • 84

3 Answers3

20

I figured out reading the code. You can send a metadata param to the function call, where metadata is a tuple of 2-tuples:

metadata = (('md-key', 'some value'),
            ('some-md-key', 'another value'))
response = stub.YourFunctionCall(request=request, metadata=metadata)
avi
  • 9,292
  • 11
  • 47
  • 84
  • 6
    More recently this needs to be a list of 2-tuples: metadata = [('k1', 'v1'), ('k2', 'v2')] – Olshansky Sep 28 '17 at 21:53
  • 2
    If you have only *one* header, like for example, `metadata = (('md-key', 'some value'))` this code will fail. You have to add them as array as follows: `metadata = [('md-key', 'some value')]` – Avión Apr 05 '19 at 14:01
  • 2
    It's not so much that the request fails but that Python won't interpret that as a 2-tuple. You can also use `metadata = (('md-key', 'some value'), )` – James S Feb 21 '20 at 02:12
8

Pls read the example in github. For example:

        response, call = stub.SayHello.with_call(
            helloworld_pb2.HelloRequest(name='you'),
            metadata=(
                ('initial-metadata-1', 'The value should be str'),
                ('binary-metadata-bin',
                 b'With -bin surffix, the value can be bytes'),
                ('accesstoken', 'gRPC Python is great'),
            ))

Or if you want to define a interceptor

        metadata = []
        if client_call_details.metadata is not None:
            metadata = list(client_call_details.metadata)
        metadata.append((
            header,
            value,
        ))
        client_call_details = _ClientCallDetails(
            client_call_details.method, client_call_details.timeout, metadata,
            client_call_details.credentials)

Something important is that the metadata's key can not has upper case character (It has troubled me for a long time).

flycash
  • 414
  • 4
  • 8
  • Direct link to the example: https://github.com/grpc/grpc/blob/master/examples/python/metadata/metadata_client.py – Attila123 Mar 12 '20 at 14:27
  • Metadata keys must be lowercase chars. That's just horrible and frustrating. `ValueError: metadata was invalid` – Donn Lee May 23 '23 at 22:46
1

If you metadata has one key/value you can only use list(eg: [(key, value)]) ,If you metadata has Mult k/v you should use list(eg: [(key1, value1), (key2,value2)]) or tuple(eg: ((key1, value1), (key2,value2))

Wollens
  • 81
  • 5