Building a RESTful JSON API with Rails and React
Introduction
In this tutorial, we will explore how to build a RESTful JSON API using the Ruby on Rails framework and integrate it with a React frontend. RESTful APIs have become a popular approach for building web services, and Rails provides a powerful framework for creating them.
Setting up the Rails Backend
To start, make sure you have Rails installed on your machine. Open up your terminal and run the following command to create a new Rails project:
$ rails new my_api
Once your project is created, navigate to its directory:
$ cd my_api
Next, generate a new scaffold for a resource. For example, to create a Todo app, run:
$ rails generate scaffold Todo title:string completed:boolean
This command will generate all the necessary files – the model, controller, and views for managing Todo items. Remember to migrate the database:
$ rails db:migrate
Implementing the API
With the scaffold in place, you now have a basic API for managing Todo items. Start the Rails server:
$ rails server
Your API is now accessible at http://localhost:3000. You can test the API endpoints using tools like cURL or Postman.
Setting up the React Frontend
To integrate React with Rails, we’ll use the npm package create-react-app
. Run this command to create a new React app:
$ npx create-react-app my_app
Once the command finishes, navigate to your React app:
$ cd my_app
Now, let’s install the necessary dependencies:
$ npm install axios react-router-dom
We’ll use Axios for making HTTP requests to our Rails API and React Router for handling navigation.
Connecting Rails API to React
In your React app, open the file src/App.js
and replace its content with:
import React, { useEffect, useState } from 'react';
import axios from 'axios';
const App = () => {
const [todos, setTodos] = useState([]);
useEffect(() => {
axios
.get('http://localhost:3000/todos')
.then(response => setTodos(response.data));
}, []);
return (
Todos
{todos.map(todo => (
- {todo.title}
))}
);
};
export default App;
This code initializes a state variable called todos
and fetches the list of Todos from our Rails API using the axios
library. The list is then rendered inside an unordered list.
Conclusion
In this tutorial, we learned how to build a RESTful JSON API with Rails and integrate it with a React frontend. Rails provides a convenient framework for building APIs, while React allows for the creation of dynamic user interfaces. By combining these technologies, we can create powerful web applications with a seamless backend/frontend integration.
Leave a Reply