Making Axios play nicely with a Rails API

Mike Parton
2 min readJan 26, 2018

--

So nice

Lately I’ve been working on a React app that goes with a Rails API and one thing that has annoyed me is that Javascript and Rails have different naming conventions for variables.

# In rails snake case is the way to goparams = {
first_name: "Mike",
last_name: "Parton"
}
// But in javascript camel case is preferredparams = {
firstName: "Mike",
lastName: "Parton"
}

For my React app to talk to the API, these params need to be the same. I could just try to remember to use snake case for all API related variables in my Javascript, but at some point I’ll inevitably make a mistake.

There’s a better solution.

I use Axios as my http client because it has a great api and some nice options for configuration. When you create an Axios client, you can pass in your own functions to transform data coming in and out of your API. Using the utility library humps it is easy to make sure that incoming data from rails is transformed to camel case and all post data is sent as snake case.

import axios from 'axios'
import humps from 'humps'
const api = axios.create({
baseURL: YOUR_API_ENDPOINT_HERE,
transformResponse: [
...axios.defaults.transformResponse,
data => humps.camelizeKeys(data)
],
transformRequest: [
data => humps.decamelizeKeys(data),
...axios.defaults.transformRequest
]
})

Axios comes with it’s own transformation functions which need to be applied as well. The order is important to make sure that our transformations aren’t run on the stringified data object.

With this setup, I can now use my API and never have to worry about Rails naming conventions in my Javascript.

--

--