- Lab
-
Libraries: If you want this lab, consider one of these libraries.
- Core Tech
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 Info
Table of Contents
-
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.pieInventoryreturns every pie's id, name and price,pieRatingsreturns a pie's customer rating ornullif no one has rated it, andpieOrdersreturns 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 thesrcfolder:restClient.ts,schema.ts,resolvers.ts,queries.tsandserver.ts. ### Checking Your Progress as You WorkEvery 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=dotCheck your types:
npm run typecheckThe 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 exampleTask 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+Cto stop it before you run these commands. ### Calling the REST Modules DirectlyBefore 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
fetchPieByIdfor the pie andfetchOrdersForPiefor its orders, then merges the two results itself.src/restClient.tsholds that client. ### What the REST Client Had to DoThe 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, thenfetchOrdersForPie| One query, such aspie(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 | Anerrorsarray alongside anydata| | 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.
-
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.
typeblocks describe object shapes, and a specialtype Querylists every entry point a client can call. A field type that ends in!is non-null, and one without it is nullable.src/schema.tsassembles the gateway's SDL from three functions, and the first ispieTypeDefs. It declares aPietype whose fields are all required, aPieFilterInputthat a later step uses to narrow the catalog by price, and aQuerytype with a filterablepieslist and a single-piepie(id)lookup.info>
priceis aFloathere 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 asMoney. ### Resolvers Turn Schema Fields into REST CallsA schema alone cannot produce data. A resolver is a function that returns one field's value, and
src/resolvers.tsholds every resolver in the gateway.resolvePiesis the resolver behindQuery.pies. It calls the inventory REST module, maps each record onto thePieshape and passes the list throughapplyPieFilter, which returns the list unchanged until Step 4 adds real filtering. ### A Second Resolver for the Same REST SourceQuery.pie(id)needs its own resolver,resolvePieById, even though it reads the samepieInventorymodule asresolvePies. One REST source can back several schema fields, each with a resolver shaped for what that field promises.Query.pieis nullable, so the resolver returnsnullfor an unknown id instead of throwing. -
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 tonull, and every client can rely on that. If a resolver breaks the promise and returnsnullfor a non-null field, GraphQL doesn't send thatnull. It adds an error to the response'serrorsarray and sets the nearest nullable parent field tonullinstead, which can empty out much more than the one field. A nullable field makes the opposite promise, so clients must handlenullbecause the data may not exist.nullableRatingFieldTypeDefsadds the first nullable field,Pie.rating, because not every pie has been rated. It usesextend type Pieto add a field without editing the originalPiedeclaration. ### Extending the Schema with a New TypeorderTypeDefsadds anOrdertype and anordersfield onPie.Order.customerNamestays nullable because some orders are anonymous, whileOrder.idandOrder.quantityare non-null because every order carries both.Pie.ordersis[Order!]!, so the list is nevernull, a pie with no orders returns an empty list, and no entry in the list is evernull. ### Resolver ChainingA resolver's first argument,
parent, is the value its containing type resolved to. A resolver onPie.ordersreceives the pie asparent, soparent.idselects the right REST call. Theratingresolver returns the ratings source's result unchanged, so an unrated pie still resolves tonull. Theordersresolver returns an empty list when the source has nothing, becausePie.ordersis non-null.info> Because
ratingandordersresolve once per pie, a query for all four pies with their orders makes fourfetchOrdersForPiecalls, one per pie. This is the N+1 problem. Production gateways batch those calls, typically with a DataLoader that collects everyparent.idrequested in the same tick and sends one request for all of them. -
Challenge
Step 4: Shape and Filter Responses by Selection
Query Arguments Carry the Filter
The
filter: PieFilterInputargument from Step 2 already reachesresolvePies, but nothing uses it yet.applyPieFilterinsrc/resolvers.tsturns that argument into a narrowed list. A bound is inclusive, so a pie priced exactly atminPriceormaxPricestays in the list, and a bound of0still counts as set.info>
applyPieFilterfilters in memory, afterfetchPieInventory()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 ResponseA 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.resolvePiesstill callsfetchPieInventory()and builds eachPie, but a query that selects onlynameandpricenever calls theratingorordersresolvers, 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.tsruns real query documents against the assembled schema withgraphql(), so you can see that happen.graphql()doesn't throw when a query is invalid. It returns a result whoseerrorsarray explains what went wrong, withdatamissing or incomplete. Each function you write here checksresult.errorsand throws, so a bad query fails loudly instead of quietly returningundefined.schemais typedGraphQLSchema | nullbecause it staysnullwhile the SDL is unfinished, so passschema!tographql(). 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 ResponseA response holds one value per key, so selecting
piestwice with different arguments needs two keys. Without them, GraphQL rejects the whole query before running it, with the errorFields "pies" conflict because they have differing arguments. Use different aliases on the fields to fetch both if this was intentional.An alias, written asaliasName: fieldName(...), gives each selection its own key while still calling the same field. -
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 TogetherThe 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
runGatewayOverviewQueryreturnsPecan Delightwith 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 MigrationThe gateway never replaced a REST module. Each resolver wraps one, which gives a migration path that keeps working at every stage:
- Put the gateway in front of the existing REST services and point new clients at the GraphQL endpoint. Existing REST clients keep working unchanged.
- Add one type or field at a time, with a resolver that calls the REST service that already owns that data, as
Pie.ratingandPie.ordersdid in Step 3. - Move clients from REST calls to queries one screen at a time.
- 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.
-
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.createYogabuilds that server from a schema, and the instance has afetchmethod that accepts a request without opening a port.src/server.tsholds the functions for this step. ### Introspection Shows the Typed SchemaEvery 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 kindNON_NULLwrapping the type underneath inofType. The response shows the contracts from Step 3:Pie.ratingappears as a plainSCALARnamedFloat, whilePie.idandPie.ordersappear insideNON_NULL.Pie.ordersis[Order!]!, which introspection describes asNON_NULLwrappingLISTwrappingNON_NULLwrappingOrder. This query only goes oneofTypedeep, so forordersyou see anofTypewith kindLISTand namenull, because a list has no name of its own. Another nestedofTypewould reach the innerNON_NULLand thenOrder.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.
-
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 devVite 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
fetchPieWithOrdersViaRestfrom 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
errormessage the function threw. ### Explore the Schema in GraphiQLThe dev server also serves the Yoga instance from
createGatewayYogaat/graphql. In the Web Browser tab, add/graphqlto the end of the address to open GraphiQL, Yoga's in-browser query editor.- 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 ratedPecan Delight, along with both of its orders. - 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: Floatandorders: [Order!]!. GraphiQL built that page from an introspection query like the one you wrote in Task 6.2.
Remove
/graphqlfrom the address to return to the app. ### Run the Final ChecksThe lab has one terminal, so press
Ctrl+Cto stop the server first. Then run the whole suite on the finished code:npx --no-install vitest run --reporter=dotThe summary ends with
Tests 14 passed (14). Run the type check next:npm run typecheckThe 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.
- REST: Pecan Delight with orders is
About the author
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.