graphql-python / gql

A GraphQL client in Python

Home Page:https://gql.readthedocs.io

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Set request header on request

georgyraylu opened this issue · comments

Hi. I want to be able to set headers for individual requests. Right now the only way to set header is at the client initialization level:

        headers = {}
        transport = AIOHTTPTransport(url=f"{base_url}/v1/graphql", headers=headers)
        client = Client(transport=transport, fetch_schema_from_transport=True)

        # I want to pass the headers here:
        client.execute(query, variables, headers = headers)

For example, when using the requests library. The API supports that:

       requests.post("http://www.example.com/", headers={"Content-Type":"text"})

You can modify transport.headers before each query.

See #118

@leszekhanusz, Thank you for your quick response. I have a concurrent asyncio application where multiple requests use the same Client instance. If call transport.header.update() before each request, it will create race conditions. If I protect that operation, together with client.execute with a mutex, it will kill all the benefits of a concurrent application. There should be a better approach built into the library.

We can't add a headers parameter to the execute method because the execute method is designed to send a request through a transport which is already connected.

It is supposed to work even for other type of transports where there is no http headers or where the headers are sent once at the connection and you can send multiple requests (like with websockets)

If you need multiple transports with different headers concurrently, then you should make multiple transport instances for each request, with multiple Client instances.

One way to do it would be to simply create a new Client and a new transport for each request, but another way to do it would be to create a pool of Client and transports which could be ready for any new incoming execution request.

There is an example with issue #314 but it is sync with Threads but you could do the same thing for async if you want.

Thank you for your elaborate answer. Now I understand