LoginSignup
6
7

More than 5 years have passed since last update.

How to use API's with Ruby

Last updated at Posted at 2015-03-24

Basic of HTTP

  1. The HTTP stands for HyperText Transfer Protocol.
  2. When you make an HTTP request, it zips through the Internet until it finds the server that knows how to fulfill that request. Then the server sends a response back to you!
  3. REST (or Representational State Transfer).
    • Whenever you navigate through a site by clicking links, you're making a state transition, which brings you to the next page (representing the next state of the application).
    • When something follows REST principles, we say that thing is RESTful.
  4. A RESTful API
    • API: application programming interface, is kind of like a coding contract: it specifies the ways a program can interact with an application. For example, if you want to write a program that reads and analyzes data from Twitter, you'd need to use the Twitter API, which would specify the process for authentication, important URLs, classes, methods, and so on.
  5. Making a Request

    require 'open-uri'
    # Open http://placekitten.com/ for reading on line 4!
    kittens = open("http://placekitten.com")
    body = kittens.read[559, 441]
    # Add your puts statement below!
    puts body
    

    Result:

                      __     __,
                      \,`~"~` /
      .-=-.           /    . .\
     / .-. \          {  =    Y}=
    (_/   \ \          \      / 
           \ \        _/`'`'`b
            \ `.__.-'`        \-._
             |            '.__ `'-;_
             |            _.' `'-.__)
              \    ;_..-`'/     //  \
              |   /  /   |     //    |
              \  \ \__)   \   //    /
               \__)  
    nil
    
  6. The Four Verbs

    • GET: retrieves information from the specified source.
    • POST: sends new information to the specified source.
    • PUT: updates existing information of the specified source.
    • DELETE: removes existing information from the specified source.
  7. Anatomy of a Request
    An HTTP request is made up of three parts:

    • The request line, which tells the server what kind of request is being sent (GET, POST, etc.) and what resource it's looking for;
    • The header, which sends the server additional information (such as which client is making the request)
    • The body, which can be empty (as in a GET request) or contain data (if you're POSTing or PUTing information, that information is contained here).

    Example:

    # POST /codecademy/learn-http HTTP/1.1
    # Host: www.codecademy.com
    # Content-Type: text/html; charset=UTF-8
    # Name=Eric&Age=26
    

    Note the POST information in the request line, the header information below it, and the data to be POSTed at the bottom (line 5).

  8. Endpoints are API-defined locations where particular data are stored. Just as you'll GET a pair of pants from PantsWorld or you'll GET a bag of peanuts from PeanutHut, you'll GET something different depending on the endpoint you use.

  9. Authentication & API Keys, Many APIs require an API key. Just as a real-world key allows you to access something, an API key grants you access to a particular API. Moreover, an API key identifies you to the API, which helps the API provider keep track of how their service is used and prevent unauthorized or malicious activity.
    Some APIs require authentication using a protocol called OAuth.
    example: api_key = "FtHwuH8w1RDjQpOr0y0gF3AWm8sRsRzncK3hHh9"

  10. HTTP Status Codes
    A successful request to the server results in a response, which is the message the server sends back to you, the client.
    The response from the server will contain a three-digit status code. These codes can start with a 1, 2, 3, 4, or 5, and each set of codes means something different.
    full list

    • 1xx: You won't see these a lot. The server is saying, "Got it! I'm working on your request."
    • 2xx: These mean "okay!" The server sends these when it's successfully responding to your request.
    • 3xx: These mean "I can do what you want, but I have to do something else first." You might see this if a website has changed addresses and you're using the old one; the server might have to reroute the request before it can get you the resource you asked for.
    • 4xx: These mean you probably made a mistake. The most famous is "404," meaning "file not found": you asked for a resource or web page that doesn't exist.
    • 5xx: These mean the server goofed up and can't successfully respond to your request.

    Example:

    require 'open-uri'
    placekitten = open('http://placekitten.com/')
    puts placekitten.status
    

    Result:

    200
    OK
    
  11. Anatomy of a Response
    The HTTP response structure mirrors that of the HTTP request. It contains:

    • A response line, which includes the three-digit HTTP status code;
    • A header, which includes further information about the server and its response;
    • The body, which contains the text of the response.

    example:

    # HTTP/1.1 200 OK
    # Content-Type: text/xml; charset=UTF-8
    # <?xml version="1.0" encoding="utf-8"?>
    # <string xmlns="http://www.codecademy.com/">Accepted</string>
    
  12. Parsing XML
    XML (which stands for Extensible Markup Language) is very similar to HTML—it uses tags between angle brackets. The difference is that XML allows you to use tags that you make up.

    Example:

    pets.txt

    <pets>
        <pet>
            <name>Jeffrey</name>
            <species>Giraffe</species>
        </pet>
        <pet>
            <name>Gustav</name>
            <species>Dog</species>
        </pet>
        <pet>
            <name>Gregory</name>
            <species>Duck</species>
        </pet>
    </pets>
    

    script.rb

    require "rexml/document"
    
    file = File.open("pets.txt")
    doc = REXML::Document.new file
    file.close
    
    doc.elements.each("pets/pet/name") do |element|
        puts element    
    end
    

    Resulst:

    <name>Jeffrey</name>
    <name>Gustav</name>
    <name>Gregory</name>
    [ ... ,  ... ,  ... ]
    
  13. Parsing JSON
    JSON (which stands for JavaScript Object Notation) is an alternative to XML. It gets its name from the fact that its data format resembles JavaScript objects, and it is often more succinct than the equivalent XML.

    Example:

    pets.txt

    {
    "pets": {
        "name": "Jeffrey",
        "species": "Giraffe"
        }
    }
    

    script.rb

    require 'json'
    
    pets = File.open("pets.txt", "r")
    
    doc = ""
    pets.each do |line|
        doc << line
    end
    pets.close
    
    puts JSON.parse(doc)
    

    Resulst:

    {"pets"=>{"name"=>"Jeffrey", "species"=>"Giraffe"}}
    
  14. XML or JSON?
    This leads us to wonder, though: how do we know whether an API will reply with XML or JSON?
    The only way you'll know what type of data an API will send you is to read that API's documentation! Some will reply with one, and some will reply with the other. Documentation is a programmer's best friend, and it's always in your best interest to read it so you understand that what the API expects from you and what the API intends to send you when you make a request.

References

6
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
7