loading...

Day 72 : #100DaysofCode - Still Trying To Get API To Work

sincerelybrittany profile image Brittany ・2 min read

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.

So far I was able to implement what I learned about api calls during my cli project into this project. To get started, I am using two free apis. quotes.rest and unsplash .

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"][0]["quote"]
        author = res["contents"]["quotes"][0]["author"]
        category = res["contents"]["quotes"][0]["category"]
    end 
end
The photo

@photo = "https://source.unsplash.com/random" holds the photo url for the views page.

The quote

@quote = res["contents"]["quotes"][0]["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!

Sincerely,
Brittany

Song of the day: (I was with my 1 year old nephew all day today and I love Disney haha)

Posted on by:

sincerelybrittany profile

Brittany

@sincerelybrittany

Developer | Software Engineer πŸ‘©πŸΎβ€πŸ’» | Determined | Music & Dance | Completed #100DaysofCode | #WomenWhoCode |MLH Fellow

Discussion

pic
Editor guide