CRUD REACTion with RUBY Sinatra API
Tags: react, ruby, beginners, webdev
Published: 2021-11-18 19:16:32

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/86err058h2jyd0ivs7vr.jpg)
Ruby Sinatra is a smaller alternative to Ruby on Rails, it was created and open-sourced in 2007, and has been used by companies such as Apple, LinkedIn, and GitHub. This 'microframework' focuses on creating a functional backend to frontend interface with minimal effort. When paired with REACT, it can be quite painless to maneuver and debug during CRUD (Create, Read, Update, Delete) operations.

For example, if you were to fork and clone this  [repo](https://github.com/learn-co-curriculum/phase-3-sinatra-react-project/fork) from GitHub you would have a file structure set up with [ActiveRecord](https://guides.rubyonrails.org/v5.0/active_record_basics.html) and [Sinatra](http://sinatrarb.com/), among various other gems, after you ran the command 'bundle install' within your terminal. This paired with [creating a REACT APP](https://reactjs.org/docs/create-a-new-react-app.html) would give you all of the file structures necessary to begin a full-stack web-application. For the explanations on CRUD below, I will assume you've had experience in creating migrations, seeding data, running the backend server within Sinatra and building out a front-end interface as well as running the browser from a REACT application. Examples of all of these tasks can be found in this [frontend repo](https://github.com/ADAM-MOORE97/phase-3-project-frontend) and this [backend repo](https://github.com/ADAM-MOORE97/phase-3-project-backend), both of which are built to work together for a group project within my coding bootcamp.


The below examples will be for CRUD operations from a React front end to a Sinatra backend. These examples are different from the ones used within the frontend and backend repos, they are used as in-depth explanations to the functions and operations being used within this project

Create (POST)
```React
//REACT FRONTEND
//Callback function to handle post request from client
//has new blog post object passed as parameters(name doesn't matter)
 function addBlog(newBlog) {
//Server URL with appropriate request endpoint
    fetch('http://localhost:9292/blog_post', {
//method stated for server.
      method: 'POST',
//headers clarify what type of content is being passed through request.
      headers: { 'Content-Type': 'application/json' },
//body turns object to string format for backend readability, 
//object has keys(params in ruby) that match columns for blogs table.
// newBlog will be destructured
// and 'POST'ed to backend before being returned.
      body: JSON.stringify(newBlog)
    }).then(r => r.json())
//returned data sets state variable to be all blogs
//including newly posted blog.
.then(data => setBlogs(data))
  };
```
```Ruby
#RUBY BACKEND
#Request type is specified before URL endpoint.
#URL endpoint points to all blog posts
post '/blog_post' do

#creates new instance of a Blog for the Blog class and blogs table.
   Blog.create(title: params[:title],
                content: params[:content], 
                author: params[:author])
    # return all blog posts as well as newly posted one.
    #Requests turned to JSON, for REACT readability.
    Blog.all.to_json
end
```

Read (GET)
```React
//REACT FRONTEND
//React component mounts, useEffect runs a GET request to
//the Sinatra API.
 useEffect(()=> {
//Server URL with appropriate request endpoint
    fetch('http://localhost:9292/blog_post')
.then(r => r.json())
//returned data sets state variable to be all blogs
.then(data => setBlogs(data))
  },
 []);
```
```Ruby
#RUBY BACKEND
#Request type is specified before URL endpoint.
#URL endpoint points to all blog posts
get '/blog_post' do
    # return all blog posts after request
    #Requests turned to JSON, for REACT readability.
    Blog.all.to_json
end
```


Update (PATCH)
```React
//REACT FRONTEND
//Callback function to handle patch request from client
//has new blog post object passed as parameters(name doesn't matter)
 function editBlog(blog,id) {
//Server URL with appropriate request endpoint
    fetch(`http://localhost:9292/blog_post/${id}`, {
//method stated for server.
      method: 'PATCH',
//headers clarify what type of content is being passed through request.
      headers: { 'Content-Type': 'application/json' },
//body turns object to string format for backend readability, 
//object has keys(params in ruby) that match columns for blogs table.
// blog will be destructured
// and 'PATCH'ed over in backend before being returned.
      body: JSON.stringify(blog)
    }).then(r => r.json())
//returned data sets state variable to be all blogs
//including updated(PATCHed) blog.
.then(data => setBlogs(data))
  };
```
```Ruby
#RUBY BACKEND
#Request type is specified before URL endpoint.
#URL endpoint points to specific blog post with ':id'
patch '/blog_post/:id' do

#finds appropriate blog post using :id endpoint
 update_blog = Blog.find(params[:id])
#updates the blog instance to requested params.
  update_blog.update(title: params[:title],
                content: params[:content], 
                author: params[:author])
    # return all blog posts as well as newly patched one.
    #Requests turned to JSON, for REACT readability.
    Blog.all.to_json
end
```

Delete (DELETE)
```React
//REACT FRONTEND
//Callback function to handle delete request from client
//has blog post object passed as parameters(name doesn't matter)
 function editBlog(blog,id) {
//Server URL with appropriate request endpoint
    fetch(`http://localhost:9292/blog_post/${id}`, {
//method stated for server.
      method: 'DELETE',
//headers and body not necessary for DELETE request
    }).then(r => r.json())
//returned data logged to console
//including updated(PATCHed) blog.
.then(data => console.log(data)
  };
```
```Ruby
#RUBY BACKEND
#Request type is specified before URL endpoint.
#URL endpoint points to specific blog post with ':id'
delete '/blog_post/:id' do

#finds appropriate blog post using :id endpoint
 blog = Blog.find(params[:id])
#Destroys instance of Blog found from blogs table and class
    # return all blog posts, with deleted blog no longer there.
    #Requests turned to JSON, for REACT readability.
    Blog.all.to_json
end
```

Hopefully these links and CRUD examples have been helpful to you and your full-stack application endeavors. The project links wouldn't be possible without the help of others working on the project [Jane](https://github.com/janechodance) and [Amy](https://github.com/aeposten) both of whom are great up-and-coming web-developers. Feel free to check out their GitHub profiles and repos, as well as [mine](https://github.com/ADAM-MOORE97). Happy developing!