We’ll need to add Graphiti::Rails to our Application controller so graphiti can handle parsing and serializing our requests. And we’ll register the Graphiti::Errors::RecordNotFound exception so we can return 404.

The generator will also create specs and a controller at app/controllers/posts_controller.rb. We’re going to move that to a namespaced folder app/api/v1 which will allow us to manage API versions in the future.

It’s super simple: it just pulls in our javascript and stylesheets compiled by webpacker. Then we add a div with id=“app” and a nested <app></app> so our Vue wrapper component can pick it up and render the main component.

This is the only Rails view we need to write for our application to work.

Create Models on Client

Usually when I build an SPA I’ll write services that use libraries like axios to make Ajax requests to the backend. Graphiti comes with a client library called spraypaint that handles parsing and serializing JSON:API payloads. It supports including associations, advanced filtering, sorting, statistics and more.

Let’s set it up!

yarn add spraypaint isomorphic-fetch

Next let’s create an ApplicationRecord class that will store our spraypaint configuration.

We set the baseUrl and apiNamespace to ‘’ and ‘/api/v1‘ respectively so that spraypaint uses relative paths and avoids CORS requests. It also namespaces our requests so we can manage API versions easily.

Marvellous! If we add some posts in the console and run the application we will see the posts load and render in the page.

Notice that we import our Post model and use it in our created() call like it was a Rails model. Calling Post.all() returns a promise that we can chain to set our posts and loading data properties. The spraypaint model can chain more useful methods like where and page.

Spraypaint is a very powerful library that supports pagination, sorting, statistics, complex filtering and much more. You can check out the spraypaint docs for detailed guides.

Conclusion

Standards are good. Vue is awesome, and so is Rails. Gems and libraries like Graphiti and Spraypaint make it super easy to build scalable REST APIs that comply with said standards and integrate seamlessly with frameworks like Vue.

I hope you enjoyed the article, don’t forget to like if you did. I would love to hear your thoughts or suggestions for other articles. Just leave a comment below :)