Featured resource
2026 Tech Forecast
2026 Tech Forecast

1,500+ tech insiders, business leaders, and Pluralsight Authors share their predictions on what’s shifting fastest and how to stay ahead.

Download the forecast
  • Lab
    • Libraries: If you want this lab, consider one of these libraries.
    • Core Tech
Labs

Contrasting GraphQL with REST

Bethany's Pie Shop already exposes its pie inventory, ratings and orders through small REST-style modules scattered across the codebase: async functions that stand in for its REST endpoints and return the same fixed JSON. Rather than rewrite those sources, the team wants a single GraphQL gateway, built with GraphQL Yoga, that wraps the existing REST functions one at a time. Your job is to build that gateway: define a typed schema with deliberate nullable and non-null fields, wire resolvers that call the existing REST sources, and prove through executed queries that the gateway can migrate services gradually while shaping each response to exactly what the client asks for.

Lab platform
Lab Info
Level
Beginner
Last updated
Nov 17, 2026
Duration
59m

Contact sales

By clicking submit, you agree to our Privacy Policy and Terms of Use, and consent to receive marketing emails from Pluralsight.
Table of Contents
  1. Challenge

    Step 1: Meet Bethany's Pie Shop REST Backend and the Gateway Plan

    Bethany's Pie Shop REST Backend

    Bethany's Pie Shop already runs three REST-style modules behind its storefront. In this lab they are in-process stand-ins for the shop's REST endpoints: plain async functions in src/restSources/ that return the same fixed JSON an HTTP endpoint would, so you can work without a network. pieInventory returns every pie's id, name and price, pieRatings returns a pie's customer rating or null if no one has rated it, and pieOrders returns a pie's order history.

    You will build a GraphQL Yoga gateway in front of those modules without rewriting them. The gateway owns a typed schema written in schema definition language (SDL) and a set of resolvers, which are functions that fill in each schema field by calling a REST module. A client then states exactly the fields it wants, such as { pies { name price } }, and receives exactly that shape. You edit five files in the src folder: restClient.ts, schema.ts, resolvers.ts, queries.ts and server.ts. ### Checking Your Progress as You Work

    Every task is graded automatically when you finish it, and you can run the same checks yourself at any time. In the Terminal, run one task's check with the task name in quotes:

    bash runTest.sh "task 2.1"
    

    Run every check at once:

    npx --no-install vitest run --reporter=dot
    

    Check your types:

    npm run typecheck
    

    The starter files are unfinished on purpose, so each task's check fails until you complete that task. A passing check ends with a summary such as Tests 1 passed, and each failure message starts with its task, for example Task 2.1: Return valid SDL from pieTypeDefs so it builds into a schema. The type check prints only its script header when there are no type errors, and otherwise lists each error with its file and line.

    info> The lab has one terminal. If you start the app in Step 7, press Ctrl+C to stop it before you run these commands. ### Calling the REST Modules Directly

    Before building the gateway, see what a client goes through without one. The shop's order history screen needs one pie together with its orders. Each REST module answers one question with one fixed payload, so the client calls fetchPieById for the pie and fetchOrdersForPie for its orders, then merges the two results itself. src/restClient.ts holds that client. ### What the REST Client Had to Do

    The view took two calls and a hand-written merge, and the client received every field each module returns whether the screen shows it or not. The gateway you build next changes who decides the shape of a response:

    | | REST modules | GraphQL gateway | |---|---|---| | Requests for one pie with its orders | One per module: fetchPieById, then fetchOrdersForPie | One query, such as pie(id: "pie-2") { name orders { quantity } } | | Response shape | Fixed by each endpoint | Exactly the fields the query selects | | Combining data | The client merges the payloads | Resolvers fetch each field, and GraphQL assembles one response | | Errors | An HTTP status code per request | An errors array alongside any data | | Caching | HTTP caching per URL | Usually per query or per object, handled by client libraries |

    REST isn't wrong here: each module stays simple and easy to cache. The gateway adds a layer on top that lets each client ask for the shape it needs. Step 5 fetches this same view with one GraphQL query.

  2. Challenge

    Step 2: Define the Gateway Schema and Wire the Inventory

    Schema Definition Language and the Query Root

    A GraphQL schema is written in SDL. type blocks describe object shapes, and a special type Query lists every entry point a client can call. A field type that ends in ! is non-null, and one without it is nullable. src/schema.ts assembles the gateway's SDL from three functions, and the first is pieTypeDefs. It declares a Pie type whose fields are all required, a PieFilterInput that a later step uses to narrow the catalog by price, and a Query type with a filterable pies list and a single-pie pie(id) lookup.

    info> price is a Float here to keep the schema small. Floating-point numbers can't represent most decimal amounts exactly, so production schemas usually store money as integer cents or define a custom scalar such as Money. ### Resolvers Turn Schema Fields into REST Calls

    A schema alone cannot produce data. A resolver is a function that returns one field's value, and src/resolvers.ts holds every resolver in the gateway. resolvePies is the resolver behind Query.pies. It calls the inventory REST module, maps each record onto the Pie shape and passes the list through applyPieFilter, which returns the list unchanged until Step 4 adds real filtering. ### A Second Resolver for the Same REST Source

    Query.pie(id) needs its own resolver, resolvePieById, even though it reads the same pieInventory module as resolvePies. One REST source can back several schema fields, each with a resolver shaped for what that field promises. Query.pie is nullable, so the resolver returns null for an unknown id instead of throwing.

  3. Challenge

    Step 3: Enforce Nullable and Non-Null Field Contracts

    Nullable and Non-Null Are Contracts

    A ! is a promise: a non-null field never resolves to null, and every client can rely on that. If a resolver breaks the promise and returns null for a non-null field, GraphQL doesn't send that null. It adds an error to the response's errors array and sets the nearest nullable parent field to null instead, which can empty out much more than the one field. A nullable field makes the opposite promise, so clients must handle null because the data may not exist. nullableRatingFieldTypeDefs adds the first nullable field, Pie.rating, because not every pie has been rated. It uses extend type Pie to add a field without editing the original Pie declaration. ### Extending the Schema with a New Type

    orderTypeDefs adds an Order type and an orders field on Pie. Order.customerName stays nullable because some orders are anonymous, while Order.id and Order.quantity are non-null because every order carries both. Pie.orders is [Order!]!, so the list is never null, a pie with no orders returns an empty list, and no entry in the list is ever null. ### Resolver Chaining

    A resolver's first argument, parent, is the value its containing type resolved to. A resolver on Pie.orders receives the pie as parent, so parent.id selects the right REST call. The rating resolver returns the ratings source's result unchanged, so an unrated pie still resolves to null. The orders resolver returns an empty list when the source has nothing, because Pie.orders is non-null.

    info> Because rating and orders resolve once per pie, a query for all four pies with their orders makes four fetchOrdersForPie calls, one per pie. This is the N+1 problem. Production gateways batch those calls, typically with a DataLoader that collects every parent.id requested in the same tick and sends one request for all of them.

  4. Challenge

    Step 4: Shape and Filter Responses by Selection

    Query Arguments Carry the Filter

    The filter: PieFilterInput argument from Step 2 already reaches resolvePies, but nothing uses it yet. applyPieFilter in src/resolvers.ts turns that argument into a narrowed list. A bound is inclusive, so a pie priced exactly at minPrice or maxPrice stays in the list, and a bound of 0 still counts as set.

    info> applyPieFilter filters in memory, after fetchPieInventory() has returned every pie. That leaves the REST module unchanged, which is the point of a gradual migration, but the gateway still receives the whole inventory. Once the REST service accepts query parameters such as ?minPrice=10, a production resolver would pass the filter through so the source returns less data. ### Selection Sets Shape the Response

    A query's selection set, the fields listed inside { }, decides what comes back and also what runs. GraphQL calls only the resolvers for the fields a query selects. resolvePies still calls fetchPieInventory() and builds each Pie, but a query that selects only name and price never calls the rating or orders resolvers, so the ratings and orders REST modules aren't called at all. A REST client pays for every endpoint it calls whether it uses the data or not. In the gateway, a field costs nothing until a client selects it, which is also what makes a gradual migration safe: adding a field and its REST source to the schema doesn't slow down clients that don't ask for it.

    src/queries.ts runs real query documents against the assembled schema with graphql(), so you can see that happen. graphql() doesn't throw when a query is invalid. It returns a result whose errors array explains what went wrong, with data missing or incomplete. Each function you write here checks result.errors and throws, so a bad query fails loudly instead of quietly returning undefined.

    schema is typed GraphQLSchema | null because it stays null while the SDL is unfinished, so pass schema! to graphql(). That ! is a lab convenience: a production server would build the schema once at startup and stop if it failed. ### Aliases Rename a Field in the Response

    A response holds one value per key, so selecting pies twice with different arguments needs two keys. Without them, GraphQL rejects the whole query before running it, with the error Fields "pies" conflict because they have differing arguments. Use different aliases on the fields to fetch both if this was intentional. An alias, written as aliasName: fieldName(...), gives each selection its own key while still calling the same field.

  5. Challenge

    Step 5: Reuse Selections with Fragments Across the Gateway

    Fragments Name a Selection Once

    A fragment is a named, reusable selection set. It is written fragment Name on Type { fields } and spread into any selection on that type with ...Name. It keeps two selections that need the same shape from drifting apart as the schema grows. ### Putting the Gateway Together

    The schema now has nullable and non-null contracts, resolvers chained across three REST sources, a working filter, aliases and a fragment. The last task in this step combines all of them in one query document, the way a real client would. ### REST and GraphQL Side by Side

    runGatewayOverviewQuery returns Pecan Delight with both of its orders as part of one response. In Task 1.1 the same pie and orders took two REST calls and a hand-written merge, and the client received every field both modules return. Here the client named only the fields it wanted, and the resolvers made the REST calls on its behalf, inside the gateway. ### Planning a Gradual Migration

    The gateway never replaced a REST module. Each resolver wraps one, which gives a migration path that keeps working at every stage:

    1. Put the gateway in front of the existing REST services and point new clients at the GraphQL endpoint. Existing REST clients keep working unchanged.
    2. Add one type or field at a time, with a resolver that calls the REST service that already owns that data, as Pie.rating and Pie.orders did in Step 3.
    3. Move clients from REST calls to queries one screen at a time.
    4. When a REST endpoint has no callers left, point its resolver at the underlying data source or a new service and retire the endpoint. The schema doesn't change, so clients don't notice.
  6. Challenge

    Step 6: Serve and Inspect the Schema with GraphQL Yoga

    GraphQL Yoga Serves the Schema

    Until now you ran queries by calling graphql() directly. GraphQL Yoga wraps the same schema in an HTTP server that accepts queries at /graphql, so any client can call the gateway through one endpoint. createYoga builds that server from a schema, and the instance has a fetch method that accepts a request without opening a port. src/server.ts holds the functions for this step. ### Introspection Shows the Typed Schema

    Every GraphQL schema can describe itself through introspection, which is how GraphiQL builds its documentation explorer. A query on __type(name: "Pie") returns each field with its type, and a non-null type appears as kind NON_NULL wrapping the type underneath in ofType. The response shows the contracts from Step 3: Pie.rating appears as a plain SCALAR named Float, while Pie.id and Pie.orders appear inside NON_NULL.

    Pie.orders is [Order!]!, which introspection describes as NON_NULL wrapping LIST wrapping NON_NULL wrapping Order. This query only goes one ofType deep, so for orders you see an ofType with kind LIST and name null, because a list has no name of its own. Another nested ofType would reach the inner NON_NULL and then Order.

    info> Introspection lets tools like GraphiQL learn a schema, but it also shows every type and field to anyone who can reach the endpoint. Production gateways often disable it or limit it to trusted clients.

  7. Challenge

    Step 7: Run the Application

    Start the Application

    Every task is complete, and each one was graded as you finished it. Running the whole application shows the pieces you wrote separately working together.

    In the Terminal, start the dev server:

    npm run dev
    

    Vite prints a Local: address when it is ready and serves the app on port 5173. Open the Web Browser tab. The page shows the output of your own code as JSON, one section per function:

    • REST: Pecan Delight with orders is fetchPieWithOrdersViaRest from Task 1.1: every field of both payloads, from two calls.
    • The four GraphQL sections run the query functions in src/queries.ts. Compare Gateway overview with the REST section: the same pie and orders come from one query, with only the selected fields.

    The page reloads when you save a file. If a query is invalid, its section shows the error message the function threw. ### Explore the Schema in GraphiQL

    The dev server also serves the Yoga instance from createGatewayYoga at /graphql. In the Web Browser tab, add /graphql to the end of the address to open GraphiQL, Yoga's in-browser query editor.

    1. Replace the comments in the editor with { pie(id: "pie-2") { name rating orders { quantity customerName } } } and choose the run button. The response shows "rating": null, because no one has rated Pecan Delight, along with both of its orders.
    2. Open the documentation explorer with the book icon at the top of the left sidebar, choose Query, then choose Pie. Each field shows the type you declared, such as rating: Float and orders: [Order!]!. GraphiQL built that page from an introspection query like the one you wrote in Task 6.2.

    Remove /graphql from the address to return to the app. ### Run the Final Checks

    The lab has one terminal, so press Ctrl+C to stop the server first. Then run the whole suite on the finished code:

    npx --no-install vitest run --reporter=dot
    

    The summary ends with Tests 14 passed (14). Run the type check next:

    npm run typecheck
    

    The type check prints only the script header and returns to the prompt. Congratulations on completing the lab. You called Bethany's Pie Shop's REST modules directly to see what a client has to assemble, then built a GraphQL Yoga gateway that wraps those modules behind one typed schema, resolves nullable and non-null fields, filters pies by price, and answers queries that use aliases and a shared fragment. You also served the schema through Yoga, read its types back with an introspection query, and browsed it in GraphiQL.

    The same approach lets you put a GraphQL layer in front of existing REST services and migrate them one resolver at a time while every client keeps calling a single endpoint.

About the author

Pluralsight’s AI authoring technology is designed to accelerate the creation of hands-on, technical learning experiences. Serving as a first-pass content generator, it produces structured lab drafts aligned to learning objectives defined by Pluralsight’s Curriculum team. Each lab is then enhanced by our Content team, who configure the environments, refine instructions, and conduct rigorous technical and quality reviews. The result is a collaboration between artificial intelligence and human expertise, where AI supports scale and efficiency, and Pluralsight experts ensure accuracy, relevance, and instructional quality, helping learners build practical skills with confidence.

Real skill practice before real-world application

Hands-on Labs are real environments created by industry experts to help you learn. These environments help you gain knowledge and experience, practice without compromising your system, test without risk, destroy without fear, and let you learn from your mistakes. Hands-on Labs: practice your skills before delivering in the real world.

Learn by doing

Engage hands-on with the tools and technologies you’re learning. You pick the skill, we provide the credentials and environment.

Follow your guide

All labs have detailed instructions and objectives, guiding you through the learning process and ensuring you understand every step.

Turn time into mastery

On average, you retain 75% more of your learning if you take time to practice. Hands-on labs set you up for success to make those skills stick.

Get started with Pluralsight