Connect from a Client Application¶
Overview¶
You can connect a client application to the GraphQL API to read and write data that you have exposed from a collection. This guide includes example code that demonstrates how to configure a GraphQL client and authenticate requests in common GraphQL libraries and frameworks.
Once you’ve connected your client application, you can begin to execute GraphQL operations.
Run It in CodeSandbox
You can see a working application in your browser in this
Stitch GraphQL CodeSandbox that we’ve
prepared. It uses the sample_mflix.movies
collection that’s
included in the MongoDB Atlas sample data sets.
To set up your app:
- Link a cluster that includes the Atlas sample data sets.
- Configure permissions for the
sample_mflix.movies
collection. For this demo, you can assign full read/write permissions to the default role. - Generate a collection schema for the
sample_mflix.movies
collection. Add a root-leveltitle
field to the schema with the value set to"Movie"
. - Enable anonymous authentication.
- Deploy your changes.
Once your app is set up, paste your App ID into the CodeSandbox to connect and use the GraphQL API.
Create a GraphQL Client¶
- Apollo (React)
Apollo Client is a client library that manages connections and data caching for any standard GraphQL API. Apollo packages the core components you need in a single package called apollo-boost.
You also need to add an authentication header that includes a valid Stitch user access token to each GraphQL request. You can get the access token with the Stitch browser SDK and add the header to every request with the apollo-link-context package.
To install the packages required for request authentication, run the following:
The following code shows how to import the required modules, add
Authorization headers to requests, and instantiate an
ApolloClient
that connects to a Stitch GraphQL endpoint. Make
sure to set the value of APP_ID
with your App ID.
Add the GraphQL Client to Your App¶
- Apollo (React)
Apollo provides the @apollo/react-hooks package which contains a set of
React hooks that you can use to execute GraphQL operations. The
package also contains an ApolloProvider
component that make
your ApolloClient
available to all components in your app.
To install the package, run the following:
Wrap your React application with an ApolloProvider
and pass
the client
that you created to the provider as a prop. Any
components rendered inside of the ApolloProvider
can use
Apollo React hooks.