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.

3 Answers 3

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)
3
  • 6
    More recently this needs to be a list of 2-tuples: metadata = [('k1', 'v1'), ('k2', 'v2')]
    – Olshansky
    Sep 28, 2017 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 5, 2019 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, 2020 at 2: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).

2
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))

2
  • stackoverflow.com/editing-help
    – Yunnosch
    Dec 26, 2021 at 7:51
  • please consider editing your answer to include proper formatting, and to add references and/or links to supporting materials.
    – Ouss
    Dec 29, 2021 at 10:51

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.