Building a RESTful API with Ruby & Grape

Introduction

Almost every modern application using an API to collect information, authenticate users, save information and perform additional functionality. The most common type of API is REST.

REST stands for Representational State Transfer. (It is sometimes spelled “ReST”.) It relies on a stateless, client-server, cacheable communications protocol — and in virtually all cases, the HTTP protocol is used.

In this tutorial, I’ll walk you through the basic setup of a simple RESTful API using Ruby on Rails and Grape.

Define the API

Before we begin our development, we need to figure out exactly what it is that we would like to build. For this tutorial, let’s keep it simple and build an API that can be used to manage students.

Endpoints

GET /students

This endpoint will allow us to get the list of all students we have. A simple request with no parameters.

GET /student/:student_id

GETting this resource will return all of the details we have stored for a particular student, by ID.

POST /student

This is how we will add new students to our system. The request body will describe the student’s name, address, etc.

DELETE /student/:student_id

When we no longer need a student in our system, we can remove them using this request. This will purge all data associated with the student.

For this tutorial, we will just delete the student record. However, you may wish to retain that information in case the student wants to re-enroll. You could simply mark the account status as DELETED (or something)

Setting up Rails

Grape is a RESTful API framework that sits on top of your Rails app. So before we do any coding, we need to setup a new Rails project. For this tutorial, we can call our project StudentManager.

rails new StudentManager

This command will create a new Rails app in the StudentManger directory. It will add all of the required files that Rails needs to function.

Adding Grape

Now that we have our Rails app, we need to add Grape to the project. Do so by adding the following line to your new project’s Gemfile.

gem 'grape'

Conclusion

That’s it! Super simple, and a very secure way to handle uploads without impacting your server architecture much.

If you enjoyed this post or found it helpful, definitely let me know in the comments. If not, also let me know. Don’t forget to share!

Your email address will not be published. Required fields are marked *

*