Skip to content

Gerard Altamirano

How to keep happy Rubyists and JavaScripters while working with REST APIs 🐫🐍

Tutorial, Tools, Ruby, Rails, JavaScript1 min read

Code snippet

(I don't know if JS developers are called in that way, but I wanted to keep the style) 👀

If you are here is because probably you are a Rubyist using Snake Case to work at the backend with Rails, expecting to handle all requests with that case. Or you are a Javascripter working at the frontend using Camel Case with React, Vue, or Vanilla, etc. It's also possible that you are a full-stack suffering this alone; I understand and support you, my friend.

Anyway, you wanna send JSON requests from the frontend and get responses with the same style. Also, you wanna get Snake Case at the backend and send responses in the same way. Well, fortunately in this story all of us can be happy thanks to Olive branch this is possible and it's soooo easy to use, let's do it! 👐

Adding Olive branch in your RoR project:

  1. Add it to your Gemfile 💎:

    .Gemfile
    1gem "olive_branch"

    And the bundle install

    1$ bundle install # in your project root directory
  2. Add the configuration to config/application.rb:

    config/application.rb
    1config.middleware.use OliveBranch::Middleware

    After this you must include the header Key-Inflection: camel and you'll be able to send any request using Camel Case to a REST API using ruby. Responses and request will be automatically parsed.

    1fetch(MY_URL, {
    2 headers: {
    3 "Content-type": "application/json",
    4 "Key-Inflection": "camel",
    5 },
    6});

    Thanks for reading! If you have any feedback, please email me [email protected] 😃

    BTW, I know that I wrote "surnName" lol, use your imagination and replace it with lastName, you got the point.

    📌 I recommend that you check the github repo and this other post.

© 2021 by Gerard Altamirano. All rights reserved.
Theme by LekoArts