Accessing Rails APIs in JavaScript Clients Using Rails Ranger

Victor Marques

Rails Ranger is a library I wrote that’s focused on leveraging on the defaults of Ruby on Rails APIs to make your life easier when writing javascript clients for them. It’s essentially a thin layer wrapping the powerful Axios library, while still exposing its full power for you.

Installation

$ yarn add rails-ranger

# or
$ npm install —-save rails-ranger

Basic Setup

The most basic setup would be something like that:

api-client.js

import RailsRanger from 'rails-ranger'

const config = {
  axios: { baseURL: 'http://api.myapp.com' }
}

export default new RailsRanger(config)

One important note here is that anything you send inside the axios option will be handed down to Axios as it is, so you can configure it as you want.

Usage

Then how do we start making requests? Like this:

some-front-end-component.js

import api from 'api-client'

api.list('users').then((response) => {
  // your code
})

So let’s break down what’s happening here:

  1. We import the client we’ve set up in the previous file seen in the configuration section.
  2. We call the list function from it, which is just an alias for index. This will trigger a request to the http://api.myapp.com/users URL.
  3. The JSON we receive inside response.data will have all its keys converted to snake case automatically for you!

Also, you can make use of nested resources with something like this:

api.resource(users, 1)
   .list('blogPosts', { hideDrafts: true })
   .then((response) => {
  // your code
})

And this would make a request to:

http://api.myapp.com/users/1/blog_posts&hide_drafts=true

Notice that Rails Ranger converted your resource and parameters from camel case to snake case, so each part of your app (client and API) can talk in its preferred standards.

Everybody’s happy! 🎉

More Features

Other things you can do with Rails Ranger include using namespaced routes, interpolating into the URL and making raw HTTP requests.

You can see the full list of actions and methods of Rails Ranger at our comprehensive documentation. 😄

Bonus: Using Rails Ranger as a Path Builder

You can also use Rails Ranger as just a path builder and handle the requests yourself with your favorite client:

import { RouteBuilder } from RailsRanger
const routes = new RouteBuilder

route = routes.create('users', { name: 'John' })
// => { path: '/users', params: { name: 'John' }, method: 'post' }

Making AJAX requests to a Ruby on Rails API can be fun if we leverage the well-stablished standards of the framework.

This way we can free ourselves from handling repetitive tasks like converting between camel case and snake case and focus on accessing endpoints in a semantic way. 🤠

  Tweet It

🕵 Search Results

🔎 Searching...

Sponsored by #native_company# — Learn More
#native_title# #native_desc#
#native_cta#