Introduction to GraphQL Server
Introduction to GraphQL with graphql-ruby and Sinatra
In this lesson, we will define basic types and write simple queries in GraphQL using graphql-ruby and Sinatra. By the end, you'll have created a basic GraphQL server to fetch a list of books, building on what you've learned about setting up a GraphQL server.
Creating the GraphQL Server
We'll start by setting up a new GraphQL server using graphql-ruby and Sinatra to manage our GraphQL endpoint. Let's do it step by step.
-
Define the GraphQL schema:
RubyIn this schema:
- The
BookTypeclass defines a book type withtitleandauthorfields, both of which are strings. - The
QueryTypeclass includes abooksfield that returns an array of book objects. - The resolver for the
booksquery returns an array of book hashes.
- The
-
Initialize and configure the server:
RubyThis code:
- Sets up a
Sinatraserver listening on port4000. - Creates a
POSTendpoint at/graphqlthat accepts GraphQL queries. - Parses the incoming request, executes the query against our schema, and returns the result as JSON.
- Sets up a
Running Queries Against the Server
With the server running, let's write and execute a query to fetch the list of books.
This script:
- Uses the
<<~GRAPHQLheredoc syntax to define a multi-line string for the query. The<<~allows you to write the query across multiple lines with proper indentation, making it more readable than a single-line string. TheGRAPHQLis just a delimiter (you could use any word) that marks where the string ends. The~character means Ruby will automatically remove leading whitespace, keeping your code clean. - Sends a
POSTrequest to the server with a query to fetch books. - Logs the response, which should include the list of books with their titles and authors.
The script outputs:
This output confirms that our server correctly handles the query and returns the expected data.
Lesson Summary
In this lesson, we:
- Created a schema with a basic type (
Book). - Set up resolvers to fetch data.
- Wrote and ran queries to retrieve a list of books.
Next, you will practice what you've learned by tackling exercises that help solidify these concepts. The following lessons will cover more complex queries and mutations.
Happy coding!
