This is my first attempt at getting data back from an API, and getting the data to output to a view.
I want to put an ISBN number into a search form and get the data back for that particular book using http://isbndb.com/. This is what I have so far:
Controller:
require 'open-uri'
class BookController < ApplicationController
def searchbook
resp = open("http://isbndb.com/api/books.xml?access_key=#{'API KEY HERE'}&results=texts&index1=isbn&value1=#{params[:isbn]}")
doc = Nokogiri.XML(resp.read)
# ... process response here
end
end
Form:
<%= form_tag({:controller => 'book', :action => 'searchbook'}, {:method => 'get'}) do |select| %>
<%= label_tag :isbn, "Enter ISBN Number" %>
<%= text_field_tag :isbn, params[:isbn] %>
<%= submit_tag "Search" %>
<% end %>
The XML to be returned
<?xml version="1.0" encoding="UTF-8"?>
<ISBNdb server_time="2005-07-29T03:02:22">
<BookList total_results="1" page_size="10" page_number="1" shown_results="1">
<BookData book_id="paul_laurence_dunbar" isbn="0766013502">
<Title>Paul Laurence Dunbar</Title>
<TitleLong>Paul Laurence Dunbar: portrait of a poet</TitleLong>
<AuthorsText>Catherine Reef</AuthorsText>
<PublisherText publisher_id="enslow_publishers">Berkeley Heights, NJ: Enslow Publishers, c2000.</PublisherText>
<Summary>A biography of the poet who faced racism and devoted himself to depicting the black experience in America.</Summary>
<Notes>"Works by Paul Laurence Dunbar": p. 113-114. Includes bibliographical references (p. 124) and index.</Notes>
<UrlsText></UrlsText>
<AwardsText></AwardsText>
</BookData>
</BookList>
</ISBNdb>
How do I process an XML request or what can I read to find out how?
Where can I view the data being returned in the console (if any)? I’m not even sure that this is doing anything as yet, however upon clicking “search” in my form I am taken to the searchbook action which is a blank page for now.
I may be a long way off from the whole answer but this is my first time doing this.
Parsing the XML is easy:
Which outputs:
[{:book_id=>"paul_laurence_dunbar", :isbn=>"0766013502", :title=>"Paul Laurence Dunbar", :titlelong=>"Paul Laurence Dunbar: portrait of a poet", :authorstext=>"Catherine Reef", :publishertext=>"Berkeley Heights, NJ: Enslow Publishers, c2000.", :summary=> "A biography of the poet who faced racism and devoted himself to depicting the black experience in America."}]This code was based on the idea you might be receiving multiple
<BookData>blocks, so it returns an array of hashes. If you’ll only have one use:The output now looks like:
{:book_id=>"paul_laurence_dunbar", :isbn=>"0766013502", :title=>"Paul Laurence Dunbar", :titlelong=>"Paul Laurence Dunbar: portrait of a poet", :authorstext=>"Catherine Reef", :publishertext=>"Berkeley Heights, NJ: Enslow Publishers, c2000.", :summary=> "A biography of the poet who faced racism and devoted himself to depicting the black experience in America."}