Hosting your sinatra backend(API) with heroku

ckawara

Catherine Kawara

Posted on July 3, 2022

Hosting your sinatra backend(API) with heroku

I was recently tasked with a full-stack project that incorporated the use of a react front end and ruby backend. The backend would use Sinatra and active records for migrations, database handling, and endpoint creation. Then host it to get the API to be consumed by our react front-end. The most challenging part of this project was hosting the API and that is what I will talk about today.
Here's the repository to this project

Assuming that you have your project set up,

Create Heroku Account
This is a pretty straightforward process, and can be done here

Create a new app
Once the account is set up, proceed to create a new Heroku app. You can do this in many ways, but the easiest is using the GUI. Give the app the name you'd want your API to be called.

Connect your project to Heroku
There are various ways to do this, as you can find here, but for this example, we will use the CLI, for simplicity.

  • Install Heroku CLI with npm install -g heroku
  • Log in to your Heroku account heroku login
  • clone your project's source code to your local machine
heroku git:clone -a your-project 
cd your-project
Enter fullscreen mode Exit fullscreen mode
  • Make some changes to the code you just cloned and deploy them to Heroku using Git.
git add .
git commit -am "make it better"
git push heroku master
Enter fullscreen mode Exit fullscreen mode

Configure database
In your database.yml file, set the adapter to the sql language of your choice. Postgres, sqlite3,MySQL or oracle. note that using sqlite3 will be problematic if you want to use this API in production.
I would suggest using Postgres

Add Postgres gem to your gem file
Add this using gem 'pg' so it will be included when installing the gems

Add procfile
In your file set up, add a file called Procfile this is in charge of running the entry points in any Heroku web app. In our case, the config.ru

Add command to profile
Add this to your profile so that when you push your work to production, it can be executed first.

web: bundle exec rackup config.ru -p $PORT
release: bundle exec rake db:migrate
Enter fullscreen mode Exit fullscreen mode

the first line will run our config.ru
the second line will run to run migrations and execute the schema.

Add a Postgres extension on Heroku

On your Heroku account,

  • Go to resources
  • Search Postgres, and pick the first suggestion (Heroku Postgres)
  • Add extension and submit the order form This extension will be managing your database in production

And we're done, once all this is set up, push your code to Heroku, check your logs and test out your API.

Till next time, Happy coding ✌

💖 💪 🙅 🚩
ckawara
Catherine Kawara

Posted on July 3, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related