Search code examples
graphqlapollo-serverapollo-gatewaynetflix-dgsgraphql-federation

Querying GraphQL Microservice with API key?


I have developed two Netflix DGS GraphQL Microservices and Apollo Gateway on top of these two microservices to make them as an federated graphql. I have a client application that is trying to query both the graphql microservices. And both microservices have a unique API key. How do we assign API key for multiple microservices either from client or Apollo server ? When client queries for more than one microservices with API key, there is a chance of ignoring API key by server. Is there any best practices to handle API key management?


Solution

  • Apollo Gateway has buildService property which you can use to modify request behavior using standard callbacks like willSendRequest.

    Using willSendRequest you can match service url and append API key accordingly:

    class RequestHander extends RemoteGraphQLDataSource {
        willSendRequest({ request }: { request: GraphQLRequest }) {
            // if request.http.url matches url of a service which you
            // use, add api-key to headers, e.g.
            if (request.http.url === 'http://localhost:3001') {
                request.http.headers.set('api-key', <API_KEY>)
            }
        }
    }
    
    const main = () => {
        const gateway = new ApolloGateway({
            buildService: ({ url }) => new RequestHander({ url }),
            serviceList: [
                { name: 'service1', url: 'http://localhost:3001' },
                { name: 'service2', url: 'http://localhost:3002' },
            ],
        })
    
        const server = new ApolloServer({ gateway })
    
        void server.listen({ port: 3000 }).then(({ url }) => {
            logger.info(`Apollo Gateway ready at ${url}`)
        })
    }
    
    main()
    

    This way you can create some map where you'll have all services with its api keys listed, and then you'll be able to match url and api key in willSendRequest callback in a simple way.