Techie May 2022
Prerequisites
- Ubuntu 18.04
- Ruby 3.1.0
- Rails 7.0.2.4
- MySQL
NB: You’re at liberty to experiment with other versions and databases.
Create the Rails API Project
1 . Create a new Rails 7 API project
2 . Configure session store
Open config/application.rb and add these three lines
3 . Create the Database
Configure CORS
Configure CORS to allow frontend to make requests
1 . Uncomment the rack-cors gem in the Gemfile
2 . Run bundle install
3 . Uncomment the following code in config/initializers/cors.rb file
Install Graphql
1 . Add graphql in the Gemfile
2 . Add graphiql-rails within the development dependencies in the Gemfile
Graphiql is the graphql UI that enables interaction with the API endpoints via the browser.
3 . Add sprockets
An API cannot render any page in the browser. Therefore, to get the GraphiQL editor to work, you must add sprockets to config/application.rb
4 . Install gems
5 . Install graphql boilerplate code
6 . Create a config directory in app/assets and create a manifest.js file in it
The manifest.js file specifies additional assets to be compiled and made available to the browser.
The -p and -f flags will instruct the commands to skip creating the directory and the file respectively if they already exist.
7 . Open app/config/manifest.js and add this
8 . Mount the GraphiQL engine in the development environment in the routes:
This enables access to the GraphiQL UI in the browser
9 . Test the GraphQL endpoint via the graphiql ui
Restart your development server, open the browser and navigate to localhost:3000/graphiql You should see something similar to this:
10 . Test the API
Clear out the default text in the editor’s left pane and type in the following query:
Click the Play button to execute the query, you should receive a response as shown below:
That’s it! You have successfully set up a graphql Rails 7 API.
Thanks for reading, see you in the next one!