Creating a basic API with Ruby on Rails is a quick and simple process. So let’s dive in!
Make sure that you have Rails installed. To do so, run gem install rails
.
In your terminal, run rails new [name] --api
.
The [name] will be your Rails directory name. In this article, we’ll walk through creating an example case together. We’re going to build a basic API containing data about forests and their trails.
Thus, we’ll run rails new forest-trails --api
.
Note: this example illustrates a one-to-many relationship. More on relationships in step 5.
Run rails g resource [name] [attribute] [attribute]
.
In our example case, we’ll create two resources: “Forest” and “Trail”. The [name] spot should be populated with your desired database table name. The [attribute] spots should be populated with the attributes (think database table columns) that your resource needs.
In our example, we’ll first run: rails g resource Forest name state
.
Next, we’ll run rails g resource Trail name state
.
Note: the default data type for attributes is a string. You’ll need to tweak your syntax if you want a different data type. E.g. rails g resource Trail name state _miles:integer_
.
Once you create your resources, controller files (inside “app” -> “models”) and migration files (inside “db” -> “migrate”) will be generated.
#ruby-on-rails #ruby #api