The Basics of Creating a Full CRUD API with Ruby Sinatra

Summary of RESTful Convention

API in Sinatra

  • create a new folder and navigate your terminal to it
  • inside the folder create a file called server.rb
  • install sinatra gem install sinatra

Our Model

require 'sinatra'## Model/Datasetposts = [{title: "First Post", body: "content of first post"}]

The Index Route

require 'sinatra'## Model/Datasetposts = [{title: "First Post", body: "content of first post"}]
## Index route
get '/posts' do
# Return all the posts as JSON
return posts.to_json
end
  • run the server ruby server.rb
  • go to localhost:4567/posts in your browser

The Show Route

require 'sinatra'## Model/Datasetposts = [{title: "First Post", body: "content of first post"}]
## Index route
get '/posts' do
# Return all the posts as JSON
return posts.to_json
end
## Show Route
get '/posts/:id' do
# return a particular post as json based on the id param from the url
# Params always come to a string so we convert to an integer
id = params["id"].to_i
return posts[id].to_json
end
  • run the server and test out /posts/0

The Create Route

require 'sinatra'## Model/Datasetposts = [{title: "First Post", body: "content of first post"}]## Custom Method for Getting Request body
def getBody (req)
## Rewind the body in case it has already been read
req.body.rewind
## parse the body
return JSON.parse(req.body.read)
end
## Index route
get '/posts' do
# Return all the posts as JSON
return posts.to_json
end
## Show Route
get '/posts/:id' do
# return a particular post as json based on the id param from the url
# Params always come to a string so we convert to an integer
id = params["id"].to_i
return posts[id].to_json
end
## Create Route
post '/posts' do
# Pass the request into the custom getBody function
body = getBody(request)
# create the new post
new_post = {title: body["title"], body: body["body"]}
# push the new post into the array
posts.push(new_post)
# return the new post
return new_post.to_json
end
  • using a tool like postman make a post request to /posts, make sure to include a proper json body
{
"title": "Another Post",
"body":"content in the new post"
}

The Update Route

require 'sinatra'## Model/Datasetposts = [{title: "First Post", body: "content of first post"}]## Custom Method for Getting Request body
def getBody (req)
## Rewind the body in case it has already been read
req.body.rewind
## parse the body
return JSON.parse(req.body.read)
end
## Index route
get '/posts' do
# Return all the posts as JSON
return posts.to_json
end
## Show Route
get '/posts/:id' do
# return a particular post as json based on the id param from the url
# Params always come to a string so we convert to an integer
id = params["id"].to_i
return posts[id].to_json
end
## Create Route
post '/posts' do
# Pass the request into the custom getBody function
body = getBody(request)
# create the new post
new_post = {title: body["title"], body: body["body"]}
# push the new post into the array
posts.push(new_post)
# return the new post
return new_post.to_json
end
## Update Route
put '/posts/:id' do
# get the id from params
id = params["id"].to_i
# get the request body
body = getBody(request)
#update the item in question
posts[id][:title] = body["title"]
posts[id][:body] = body["body"]
#return the updated post
return posts[id].to_json
end
  • make a put request to /posts/0 and include a proper json body to test

The Destroy Route

require 'sinatra'## Model/Datasetposts = [{title: "First Post", body: "content of first post"}]## Custom Method for Getting Request body
def getBody (req)
## Rewind the body in case it has already been read
req.body.rewind
## parse the body
return JSON.parse(req.body.read)
end
## Index route
get '/posts' do
# Return all the posts as JSON
return posts.to_json
end
## Show Route
get '/posts/:id' do
# return a particular post as json based on the id param from the url
# Params always come to a string so we convert to an integer
id = params["id"].to_i
return posts[id].to_json
end
## Create Route
post '/posts' do
# Pass the request into the custom getBody function
body = getBody(request)
# create the new post
new_post = {title: body["title"], body: body["body"]}
# push the new post into the array
posts.push(new_post)
# return the new post
return new_post.to_json
end
## Update Route
put '/posts/:id' do
# get the id from params
id = params["id"].to_i
# get the request body
body = getBody(request)
#update the item in question
posts[id][:title] = body["title"]
posts[id][:body] = body["body"]
#return the updated post
return posts[id].to_json
end
## Destroy Route
delete '/posts/:id' do
# get the id from params
id = params["id"].to_i
# delete the item
post = posts.delete_at(id)
# return the deleted item as json
return post.to_json
end
  • test it out by making a delete request to /posts/0

Conclusion

--

--

--

Alex Merced is a Full Stack Developer, learn more about his work at AlexMercedCoder.com

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Top Front End Development tools

Top Front End Development Tools

Keycloak Cluster Setup With kube_ping — DZone Cloud

ColorBlocks: The Web’s Color Palette on the Ethereum Blockchain

What is Infrastructure as Code (IaC)?

TryHackMe-Lockdown

Web scraping with Ruby, Python & R for machine learning and data analysis

Vodafone UK’s Web Testing Strategy

ASP.NET Core 3 - Authorization and Authentication with Bearer and JWT

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Alex Merced Coder

Alex Merced Coder

Alex Merced is a Full Stack Developer, learn more about his work at AlexMercedCoder.com

More from Medium

Which is better to use? Fetch() or Axios?

Location, Location, Location

BACK END CONCEPT

Ins and Outs of Full-Stack Web Development

Developer