Apollo GraphOS Quickstart

Build a federated GraphQL API with Apollo Federation and GraphOS


By the end of this quickstart, you'll have set up a federated GraphQL API—also known as a supergraph—that integrates data from products, users, and inventory services. Along the way, you'll learn about tools like the Rover CLI and GraphOS Studio.

Step 1. Set up Apollo Tools

This quickstart uses the following Apollo tools:

  • GraphOS Studio: This is the primary web interface for GraphOS. Studio helps you monitor, manage, and collaborate on your supergraph.

  • The Rover CLI: This is the primary command-line interface for GraphOS. Rover helps you interact with your graphs and their schemas.

  • A local version of Apollo's retail demo graph.

Create an Apollo account

To create and manage graphs with GraphOS, you need an Apollo account. If you already have an Apollo account, you can skip to the next section.

  1. Go to studio.apollographql.com and click Let's get started.

  2. Choose a signup method—either using GitHub or with an email and password. Studio then shows a signup form. Its details vary depending on your signup method.

  3. Complete the form, and click Create Account.

Install Rover

Install the latest Rover release with the appropriate command for your system:

terminal
MacOS / Unix-like
curl -sSL https://rover.apollo.dev/nix/latest | sh
terminal
Windows
iwr 'https://rover.apollo.dev/win/latest' | iex

After installing, run rover -V in your terminal to confirm it installed successfully. Verify that the printed version number matches the latest release. If it doesn't, you might need to manually delete an outdated installation.

Set up retail demo graph

Apollo's retail demo graph is a demonstration supergraph for a retail business containing services for checkout, discovery, inventory, orders, products, reviews, shipping, and users. It includes prebuilt schema and server code. Download or clone it from its GitHub repository.

To ensure you can run it locally in the next step, install the latest LTS version of Node.js.

 note
While the retail demo uses Node.js for all its services, Apollo Federation is compatible with many GraphQL server libraries. You can also federate services that use different programming languages and different server libraries.

Step 2. Start local development

In this local development step, you'll do the following:

  1. Locally run the subgraphs.

  2. Locally run your router.

  3. Query your router to ensure it's working as expected.

Run subgraphs

To start local development, you must first get the subgraphs in the retail demo up and running. From the root directory, install dependencies:

terminal
npm install

Then run the subgraphs:

terminal
npm run dev:subgraphs

In your terminal, you should see notifications for each subgraph:

terminal
Setting up [products] subgraph at http://localhost:4001/products/graphql
Setting up [orders] subgraph at http://localhost:4001/orders/graphql
Setting up [users] subgraph at http://localhost:4001/users/graphql
...

Keep these subgraphs up and running so that the router can query them.

 note
The retail demo contains the code behind each of these subgraphs, including their schemas, resolvers, and mock data. These files are provided for your reference—understanding them isn't necessary to complete this quickstart. Check out these tutorials to learn more about GraphQL schemas and resolvers.

Run router

With your subgraphs running, you can use Rover to start the router locally. To do so, use the rover dev command with the --supergraph-config and --router-config options.

The retail demo comes with supergraph-config-dev.yaml and router-config-dev.yaml YAML configuration files that include subgraph names, URLs, and router configurations.

In a different terminal window from the one where the subgraphs are running, run this command:

terminal
rover dev \
  --supergraph-config supergraph-config-dev.yaml \
  --router-config router-config-dev.yaml

When you first start the rover dev process, you'll see the following happening in the terminal:

  • Rover loads the supergraph configuration and begins watching it for changes.

    terminal
    supergraph config loaded successfully
    ==> Watching router-config-dev.yaml for changes
  • Rover obtains the provided subgraph schemas, starts sessions for each of them, and begins watching them changes.

    terminal
    starting a session with the 'discovery' subgraph
    ==> Watching ./subgraphs/discovery/schema.graphql for changes
    starting a session with the 'checkout' subgraph
    ==> Watching ./subgraphs/checkout/schema.graphql for changes
    starting a session with the 'users' subgraph
    ==> Watching ./subgraphs/users/schema.graphql for changes
    starting a session with the 'inventory' subgraph
    ==> Watching ./subgraphs/inventory/schema.graphql for changes
    starting a session with the 'orders' subgraph
    ==> Watching ./subgraphs/orders/schema.graphql for changes
    starting a session with the 'shipping' subgraph
    ==> Watching ./subgraphs/shipping/schema.graphql for changes
    starting a session with the 'products' subgraph
    ==> Watching ./subgraphs/products/schema.graphql for changes
    starting a session with the 'reviews' subgraph
    ==> Watching ./subgraphs/reviews/schema.graphql for changes
  • Rover uses Apollo Federation to compose a supergraph schema by adding subgraph schemas one at a time. Rover recomposes the supergraph schema whenever it detects subgraph changes.

    terminal
    composing supergraph with Federation v2.8.0
    successfully composed after adding the 'products' subgraph
  • When composition completes successfully, Rover starts a locally running router session and provides it with the supergraph schema. Recomposition automatically reloads the router.

    terminal
    ==> your supergraph is running! head to http://localhost:4000 to query your supergraph
     note
    If you see intermediate composition errors, ensure you've installed the latest version or Rover.

Nice! You've now got a supergraph running locally.

Query your router

To ensure everything works as expected, you can query your router in the Apollo Sandbox that Rover automatically starts up.

  1. Open localhost:4000 in a browser to access your locally running router. It should look something like this:

    The Apollo Sandbox with a prepopulated example query.
  2. Run the following query by copying and pasting it into the Operation window and then clicking the play button labeled ExampleQuery.

    GraphQL
    query ExampleQuery {
      listAllProducts {
        id
        title
        description
        mediaUrl
        variants {
          id
          price
        }
      }
    }
  3. Confirm that once you run the operation, you see the following in the Response panel on the right:

    Click to see response
    JSON
    {
      "data": {
        "listAllProducts": [
          {
            "id": "product:1",
            "title": "Air Jordan 1 Mid",
            "description": "Air Jordan 1 Mid is a blue, grey and white sneaker from the iconic jordan brand",
            "mediaUrl": "https://sneakernews.com/wp-content/uploads/2022/06/air-jordan-1-mid-university-blue-grey-dx9276-100-6.jpg",
            "variants": [
              {
                "id": "variant:1",
                "price": 600.25
              },
              {
                "id": "variant:2",
                "price": 20.12
              }
            ]
          },
          {
            "id": "product:2",
            "title": "Supreme x Tiffany & Co. Box Logo Tee",
            "description": "A classic Supreme vbox t-shirt in the signature Tiffany blue.",
            "mediaUrl": "https://encrypted-tbn2.gstatic.com/shopping?q=tbn:ANd9GcQWDHD3SSS98UAVKODaql7nrDTopfL4tcTnEltW8Yqy4hyDu4i5b70Wb3Y8-wACJIo5g-ZdRULPQKUmt7JfwiaSdgiOBz4pvU_YelKHUI4nhoXmMJPeh_tyWQ",
            "variants": [
              {
                "id": "variant:4",
                "price": 600.25
              },
              {
                "id": "variant:5",
                "price": 600.25
              },
              {
                "id": "variant:6",
                "price": 600.25
              },
              {
                "id": "variant:7",
                "price": 600.25
              },
              {
                "id": "variant:8",
                "price": 600.25
              }
            ]
          },
          {
            "id": "product:3",
            "title": "THE MACKINAC 40MM",
            "description": "Established by Detroit's historic Bayview Yacht club, the days-long Port Huron to Mackinac Island regatta is one of the longest and most grueling freshwater races in the world.\n\nNamed for this legendary competition, the Shinola Mackinac is our first watch with automatic, single-eye chronograph yacht-timer functionality.\n\nIt's a precision instrument designed to be passed on for generations—just like the tradition that inspires it.",
            "mediaUrl": "https://shinola-m2.imgix.net/images/Products/20253783-sdt-012455107/S0120253783_F2_MAIN_01.png?h=1500&w=1500&bg=f7f7f7&auto=format,compress&fit=fillmax",
            "variants": [
              {
                "id": "variant:9",
                "price": 3499.99
              }
            ]
          },
        ]
      }
    }

    This operation requests a list of all products from the products subgraph. You can remove fields like mediaUrl or add fields like releaseDate to the operation to see how the reponse changes.

    Next, you'll execute an operation that demonstrates the power of federation.

  4. Replace the example query in the Operation window with the following. Run it by clicking the play button, now labeled GetCart.

    GraphQL
      # Get the current user's cart with all the items
      # and their product info as well as the price.
      query GetCart {
        user {
          id
          username
          shippingAddress
          cart {
            subtotal
            items {
              price
              inventory {
                inStock
              }
              product {
                title
                description
                mediaUrl
              }
            }
          }
        }
      }
  5. In the Response panel, you should see an error like this: Could not locate user by id. Please specify a valid x-user-id header like user:1.

    This error appears because the operation retrieves a particular user's shopping cart given the user's ID. The operation expects the user ID to be in the request header. You can include it in the request headers in Sandbox by doing the following:

    • Open the Headers tab below the Operation editor.

    • Click + New header.

    • Enter x-user-id as the header key and user:1 as the value.

    The GraphOS Studio Explorer with a GetCart operation and headers.
  6. Rerun the request. In the Response panel, confirm you see the following:

    Click to see response
    JSON
    {
      "data": {
        "user": {
          "id": "user:1",
          "username": "User One",
          "shippingAddress": "123 Main St",
          "cart": {
            "subtotal": 620.37,
            "items": [
              {
                "price": 20.12,
                "inventory": {
                  "inStock": true
                },
                "product": {
                  "title": "Air Jordan 1 Mid",
                  "description": "Air Jordan 1 Mid is a blue, grey and white sneaker from the iconic jordan brand",
                  "mediaUrl": "https://sneakernews.com/wp-content/uploads/2022/06/air-jordan-1-mid-university-blue-grey-dx9276-100-6.jpg"
                }
              },
              {
                "price": 600.25,
                "inventory": {
                  "inStock": true
                },
                "product": {
                  "title": "Supreme x Tiffany & Co. Box Logo Tee",
                  "description": "A classic Supreme vbox t-shirt in the signature Tiffany blue.",
                  "mediaUrl": "https://encrypted-tbn2.gstatic.com/shopping?q=tbn:ANd9GcQWDHD3SSS98UAVKODaql7nrDTopfL4tcTnEltW8Yqy4hyDu4i5b70Wb3Y8-wACJIo5g-ZdRULPQKUmt7JfwiaSdgiOBz4pvU_YelKHUI4nhoXmMJPeh_tyWQ"
                }
              }
            ]
          }
        }
      }
    }
    $600.25—that must be some t-shirt.

Excellent. You've used one request to your router to get data from across different services. In the last part of this local development step, you'll learn more about how the router accomplished this.

Inspect query plans

The GetCart operation is powerful because it gathers data across various subgraphs: users, products, inventory, and more. Sandbox displays an operation's Query Plan to help you understand how the router intelligently orchestrates subrequests to these subgraphs.

A query plan is a blueprint for dividing a single incoming operation into one or more operations that are each resolvable by a single subgraph. You can view the query plan instead of the response by clicking Response and selecting Query Plan.

Apollo Sandbox shows a query plan diagram for an operation.

Query plans are a powerful tool for understanding operations, whether they're run locally or from client applications.

In the next step of this tutorial, you'll publish your locally running subgraph schemas to GraphOS Studio to learn more about your supergraph.

Step 3. Publish your subgraphs

To create a supergraph, you individually publish each subgraph schema to GraphOS. Whenever you publish a subgraph schema, GraphOS attempts to compose all the latest subgraph schemas into a single supergraph schema. If this composition succeeds, GraphOS updates your router with the result.

In this step, you'll create an empty supergraph in GraphOS Studio and then publish subgraph schemas to it using Rover.

Create supergraph

Before publishing subgraphs, you must first create an empty supergraph to publish them to.

  1. Go to studio.apollographql.com and click + Create New Graph.

  2. Enter a Graph title, for example Federation Quickstart. Leave the Graph Architecture as Supergraph (Default) and Visible to Team Members as On. Click Next.

  3. A Publish your schema using Federation dialog appears. Copy the entire example code block to a local text file using the copy button.

    A dialog from GraphOS Studio displays a hidden API key and graph ref.

    It should look something like this:

    terminal
    APOLLO_KEY=service:Federation-Quickstart:••••••••••••••••••••• \
    rover subgraph publish Federation-Quickstart@current \
    --schema ./products-schema.graphql \
    --name your-subgraph-name \
    --routing-url http://products.prod.svc.cluster.local:4001/graphql
    • The protected value that appears after APOLLO_KEY= and begins with service: is your graph API key.

    • The value that appears after rover subgraph publish is your graph ref. By default, it ends with @current.

    • The --schema option specifies the path to the schema file to publish.

    • The --name option specifies the name of the subgraph.

    • The --routing-url is the address the router should send subrequests for this particular subgraph to.

    You'll use both your graph API key and graph ref in the next step. The correct --schema, --name, and --routing_url will be provided.

    ⚠️ caution
    API keys are secret credentials. Never share them outside your organization or commit them to version control. Delete and replace API keys that you believe are compromised.
  4. Leave the dialog open; you'll complete setup with Rover.

Publish subgraph schemas

Complete the next steps back in your terminal:

  1. Ensure your subgraphs are still running locally.

  2. Take the multi-line command you copied from Studio:

    terminal
    APOLLO_KEY=service:Federation-Quickstart:••••••••••••••••••••• \
    rover subgraph publish Federation-Quickstart@current \
    --schema ./products-schema.graphql \
    --name your-subgraph-name \
    --routing-url http://products.prod.svc.cluster.local:4001/graphql

    and replace the last three lines with the following:

    terminal
    --schema ./subgraphs/products/schema.graphql \
    --name products \
    --routing-url http://localhost:4001/products/graphql

    It should now look something like this:

    terminal
    APOLLO_KEY=service:Federation-Quickstart:••••••••••••••••••••• \
    rover subgraph publish Federation-Quickstart@current \
    --schema ./subgraphs/products/schema.graphql \
    --name products \
    --routing-url http://localhost:4001/products/graphql
     note
    In a production supergraph, a subgraph's routing-url is generally its public endpoint.
  3. While still in the retail demo's root directory, open a new terminal window. Paste and run your updated multi-line command.

    • Because the command provides a localhost address for the routing-url, the terminal will confirm that you want to publish. Enter Y.

    • If the command is successful, you'll see the following in your terminal:

      terminal
      A new subgraph called 'products' was created in <GRAPH_REF>
      The supergraph schema for <GRAPH_REF> was updated,
      composed from the updated 'products' subgraph
      Monitor your schema delivery progression on studio: <STUDIO_URL>
    • After a few moments, the GraphOS Studio dialog you left open when creating an empty supergraph will show Schema published on the bottom left and a button to See schema changes on the bottom right. You don't need to click it right now.

      A dialog from GraphOS Studio updates to show a schema has been published.

      You can continue to publish new subgraphs to the same supergraph via Rover. There's no need to create or add new graphs in Studio.

  4. Since you're publishing to the same supergraph, you no longer need to include the first line containing your graph API key in subsequent Rover commands. Run the rover subgraph publish command for the inventory subgraph, substituting your graph ref:

    terminal
    rover subgraph publish <GRAPH_REF> \
    --schema ./subgraphs/inventory/schema.graphql \
    --name inventory \
    --routing-url http://localhost:4001/inventory/graphql
    
  5. Do the same for the users subgraph, substituting your graph ref:

    terminal
    rover subgraph publish <GRAPH_REF> \
    --schema ./subgraphs/users/schema.graphql \
    --name users \
    --routing-url http://localhost:4001/users/graphql

Congrats! With these subgraphs published, you can explore and interact with them and the supergraph composed of them in GraphOS Studio.

 note
The retail demo contains other subgraphs—for example, the reviews and shipping subgraphs. The three you've just published are enough to understand what GraphOS Studio has to offer, but you can publish the others if you want to explore their schemas.Outside of a demo environment, different teams may independently manage and publish different subgraphs.

Step 4. Explore your supergraph

Once you've published subgraphs, open the Schema page from the left nav in Studio to explore the composed supergraph schema as well as individual subgraph schemas and the relationships between them.

  • The Reference tab lets you view and filter your schema's type and field definitions. For example, select Objects, then User, to see all of the user type's fields and which subgraphs provide them.

    The GraphOS Studio Schema Reference page shows filterable list of types and fields.
  • The SDL tab displays your supergraph's API schema and supergraph schema, filterable by subgraph. Viewing the supergraph SDL (Schema Definition Language) allows developers to see exactly how subgraph schemas are composed together.

    The GraphOS Studio Schema SDL page has a left nav listing all subgraphs.
  • The Visualization tab provides a filterable, navigable, graphical representation of your supergraph schema. Once you start collecting metrics on your supergraph, you can use the visualization tool to create heatmaps to identify fields that are most frequently used, or have the highest latency or errors.

The GraphOS Studio Schema Visualization page shows an interactive representation of an e-commerce supergraph schema including Orders, Users, Variants, Products, etc.

GraphOS also offers tools for managing your schema, including schema proposals, checks, and linting. Additionally, GraphOS schema delivery tools help you integrate schema publication into your DevOps workflows.

Once you deploy your router, either by self-hosting it or using the Apollo-managed cloud option, you can use it to collect and export telemetry to GraphOS Studio and other observability and application performance monitoring (APM) tools.

Next steps

Depending on your goals, you have several options for learning more about GraphOS' capabilities or moving your supergraph closer to production:

Feedback

Forums