§2023-03-01
- [Creating a Full CRUD API with Ruby Sinatra(https://dev.to/alexmercedcoder/creating-a-full-crud-api-with-ruby-sinatra-15b4)
¶Summary of RESTful Convention
Name of Route | Request Method | Endpoint | Result |
---|---|---|---|
Index | GET | /model | returns list of all items |
Show | GET | /model/:id | returns item with matching id |
Create | Post | /model | creates a new item, returns item or confirmation |
Update | Put/Patch | /model/:id | Updated item with matching ID |
Destroy | Delete | /model/:id | Deletes item with matching ID |
- server.rb as
require 'sinatra'
## Model/Dataset
posts = [
{title: "First Post", body: "content of first post"},
{title: "Second Post", body: "content of second post"},
{title: "Third Post", body: "content of third 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
-
run it with
rerun ruby server.rb
-
test with
[curl](https://www.codejava.net/rest-api/curl-for-testing-crud-rest-apis)
- test retrieve(R)
$ curl -i localhost:4567/posts
HTTP/1.1 200 OK
Content-Type: text/html;charset=utf-8
Content-Length: 165
X-XSS-Protection: 1; mode=block
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
Connection: keep-alive
Server: thin
[{"title":"First Post","body":"content of first post"},{"tille":"Second Post","body":"content of second post"},{"tille":"Third Post","body":"content of third post"}]
$ curl -v localhost:4567/posts/1
* Trying 127.0.0.1:4567...
* connect to 127.0.0.1 port 4567 failed: Connection refused
* Trying [::1]:4567...
* Connected to localhost (::1) port 4567 (#0)
> GET /posts/1 HTTP/1.1
> Host: localhost:4567
> User-Agent: curl/7.87.0
> Accept: */*
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 200 OK
< Content-Type: text/html;charset=utf-8
< Content-Length: 55
< X-XSS-Protection: 1; mode=block
< X-Content-Type-Options: nosniff
< X-Frame-Options: SAMEORIGIN
< Connection: keep-alive
< Server: thin
<
* Connection #0 to host localhost left intact
{"tille":"Second Post","body":"content of second post"}
$ curl -X POST -H "Content-Type: application/json" -d "{\"tille\": \"Fourth Post\", \"body\": \"content of fourth post\"}" localhost:4567/posts
{"title":null,"body":"content of fourhttp://localhost:4567/posts
$ curl http://localhost:4567/posts
[{"title":"First Post","body":"content of first post"},{"title":"Second Post","body":"content of second post"},{"title":"Third Post","body":"content of third post"},{"title":null,"body":"content of fourth post"}]
$ curl -X DELETE http://localhost:4567/posts/0
{"title":"First Post","body":"co
$ curl localhost:4567/posts
[{"title":"Second Post","body":"content of second post"},{"title":"Third Post","body":"content of third post"},{"title":null,"body":"content of fourth post"}]
$ curl -X PUT -H "Content-Type: application/json" -d "{\"title\": \"Fourth Post\", \"body\": \"content of fourth post\"}" localhost:4567/posts/2
{"title":"Fourth Post","body":"content of fourth post"}
- test Create with `curl -H`
curl -X POST -H "Content-Type: application/json" -d "{"title": "Fourth Post", "body": "content of fourth post"}" localhost:4567/posts/
curl -X PUT -H "Content-Type: application/json" -d "{"title": "Fourth Post", "body": "content of fourth post"}" localhost:4567/posts/2
{\"tille\": \"Fourth Post\", \"body\": \"content of fourth post\"}
curl -X POST -i -d "userId=10&title=Hello World&body=This is the body." https://jsonplaceholder.typicode.com/posts
curl -d 'id=1&name=create' http://localhost:8080/new
curl -X POST -i -d "title=Fourth Post&body=content of fourth post" http://localhost:4567/posts
curl -X DELETE http://localhost:4567/posts/0