Today I focused on my photo application again. I am still trying to figure out exactly how to implement my api and where to put my api calls for my application. The goal is to have a picture and a quote show under the photo and a user to be able to add the picture and quote to their page.
I just wanted to see if I could make an api call today and luckily I was able to! I created a photos controller and within the photos#index I added the following code:
class PhotosController < ApplicationController def index @photo = "https://source.unsplash.com/random" url = "https://quotes.rest/qod" uri = URI.parse(url) response = Net::HTTP.get_response(uri) res = JSON.parse(response.body) @quote = res["contents"]["quotes"]["quote"] author = res["contents"]["quotes"]["author"] category = res["contents"]["quotes"]["category"] end end
@photo = "https://source.unsplash.com/random" holds the photo url for the views page.
@quote = res["contents"]["quotes"]["quote"] holds the quote! I made an
Net::HTTP request to the api and was able to get the quote along with the author and category provided by the quotes.rest api. I know all of this is very messy and needs to be out of my controller BUT I am proud of myself that I was able to make two calls to an api and show it in my views like this:
<h1> This is photos index </h1> <div class="cards"> <% 20.times do %> <div class="card"> <img src="<%= @photo %>" alt="random" > <br/> <p> <%= @quote %> </p> </div> <% end%> </div>
This is the beginning of a beautiful friendship with rails and apis.
As always, thanks for reading!
Song of the day: (I was with my 1 year old nephew all day today and I love Disney haha)