Site icon Gaurav Goyal

How I created an API in less than an HOUR!

Check out the API on https://city-api.herokuapp.com/

Okay, first things first, 2 days back one of my friends asked me to help in building an application where he was using some API to make calls and do some “stuff”. Sure, I helped him. But with that I was wondering what would it take to build an API of my own.

Then, today I was looking for some of the methods available for forms, where you have to first select COUNTRY and then CITIES load asynchronously.

Interestingly, most of the methods that exist require you to store the information in your own database (BUT, this puts extra load on your database, and you don’t even need this data unless user is filling forms). So I though why not create an API for that!

Enough with the reason, for why I created the API!

Let’s start building one.

Environment:

Application Framework: Ruby on Rails

Database: postgreSQL

Hosting Provider: Heroku

Text Editor: Sublime Text 3

Command – rails g model city name:string country:string

Command – rails g controller city 

get ’/’ => ‘city#index’.

 gem ‘pg’

require ‘csv’

puts “Importing countries…”
num = 1
CSV.foreach(Rails.root.join(“countries.csv”), headers: true) do |row|
City.create! do |city|
city.id = num
city.country = row[0]
city.name = row[1]
num += 1
end
end

The below mentioned content helps the application to generate response in accordance with the API request. SQL query is made depending upon the parameters and a JSON response is generated for the user.

def index
if params[:country].present?
@cities = City.where(‘country ILIKE ?’, params[:country]).pluck(:name)
if @cities.present?
respond_to do |format|
format.html { render json: @cities, status: :ok }
format.json { render json: @cities, status: :ok }
end
else
respond_to do |format|
format.html { render json: [“Error”], status: :not_found }
format.json { render json: [“Error”], status: :not_found }
end
end
end

if params[:city].present?
@country = City.where(‘name ILIKE ?’, params[:city]).pluck(:country)
if @country.present?
respond_to do |format|
format.html { render json: @country, status: :ok }
format.json { render json: @country, status: :ok }
end
else
respond_to do |format|
format.html { render json: [“Error”], status: :not_found }
format.json { render json: [“Error”], status: :not_found }
end
end
end
end

heroku git:remote -a your_heroku_app_name

git init 

git add –all

git commit -m “first commit”

git push heroku master

heroku run rake db:migrate

heroku run rake db:seed

This was one of my fastest developed application. (Writing this blog post took more time than the application :P). If you haven’t checked out the application yet go ahead give it a try https://city-api.herokuapp.com/.

If you want you can check out the git repo too, visit: cityAPI.

P.S.- Do comment for help/queries and suggestions.

Exit mobile version