Rails is the only backend framework that I've used so far to create APIs for my apps. So, I decided to write a post about how to start a project with a Rails API.
Step 1. Create the directory
mkdir my_api
Step 2. Navigate into the directory
cd my_api
Step 3. Create the Rails API
In the same directory, run:
$ rails new my_api --api
The --api flag will create the app without additional features such as views that Rails would create if you ran just rails new.
*optional: you can specify which database you want to use with the database flag, like this:
--database=postgresql
Step 4. Create Directories for Version Control
Inside the controllers directory, create an api directory.
mkdir my_api/app/controllers/api
Inside api, create a v1 directory (for version 1).
mkdir my_api/app/controllers/api/v1
If at some point you decide to change the way your API serves data, you can create a v2 folder, and change the way the API works without starting all over.
Step 5. Generate your Models and Controllers!
There are several ways to approach this with rails generators. You can choose to create models and controllers individually, by running rails g model Thing and rails g controller Thing, you can also use rails g resource Thing which will create both...or to really see the power of Rails, you can use rails g scaffold Thing (I usually avoid this because it usually generates too much for what I need).
6. Run your migrations!
In terminal:
rails db:migrate
7. Start Server!
Again in terminal, run:
rails s
and then navigate to localhost:3000
voila!
Top comments (0)