This is a guide on creating and setting up a Rails API application from scratch.

The focus will be on user login and sign up and authorizing/authenticating them with JWT (JSON Web Tokens). Keep in mind that this approach represents one of many. Let’s begin with the setup.

Setup

Let’s generate a Rails API. From the terminal, run the following command:

rails new jwt-rails-api-app --database=postgresql --api

The flag --database=postgresql is included to indicate that PostgreSQL is to be utilized as the database instead of SQLite, and the flag --api is included to indicate that this application is to be set up as an API and to avoid generating the views and view helpers since they are not necessary for an API.

Open the newly generated folder and open Gemfile. We need to include a few gems as part of the setup.

The first is to uncomment/include:

gem 'bcrypt'

Bcrypt will manage hashing the passwords for the user.

The second is to uncomment/include:

gem 'rack-cors'

This allows the Cross-Origin Resource Sharing (CORS) in the API. CORS prevents API calls from unknown origins.

And finally, include:

gem 'jwt'

From the terminal, run bundle install to install the three gems in the application.

Next, navigate to config/initializers/cors.rb and uncomment the following and also replace “example.com” with an asterisk.

#rails #ruby on rails #api #ruby #jwt

How to Build a Rails API with JWT
3.60 GEEK