HTTP request/response cycle and REST API - Women Who Code.
Resources for women who code
women who code, girls who code, ladies who code
51914
post-template-default,single,single-post,postid-51914,single-format-standard,qode-core-1.0.1,ajax_fade,page_not_loaded,,capri child-child-ver-1.0.0,capri-ver-1.6, vertical_menu_with_scroll,smooth_scroll,grid_1200,blog_installed,wpb-js-composer js-comp-ver-4.12.1,vc_responsive
 

HTTP request/response cycle and REST API

HTTP request/response cycle and REST API

HTTP Protocol

HTTP = HyperText Transfer Protocol. Hypertext = text with links. Protocol = “rules for getting something from one place to another”, in this case – for transferring web pages to your browser. We use HTTP to grab any web page on the Internet. These pages come from other computers on the Internet that store the information and are called servers. When you make an HTTP request, it finds the server that knows how to fulfill it. Then the server sends a response back to you.

Client/Server Relationship

REST and RESRful

REST = REpresentational State Transfer. REST is a set of principles. 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). That’s it! By following this simple model of clicking from page to page, you’re starting to follow REST principles. When something follows REST principles, we call it RESTful.

REST (RESTful) API

API = Application Programming Interface. Usually a REST API works pretty much the same way a website does. You make a call from a client to a server, and you get data back over HTTP protocol. For an API or web service to be RESTful, it must do the following:

  1. Separate the client from the server
  2. Not hold state between requests (= all the information necessary to respond to a request is available in each individual request: no data, or state, is held by the server from request to request)
  3. Use HTTP and HTTP methods

Basically, when people talk about Facebook API, Google API, etc. they are talking about RESTful API.

Making a Call to an API (example):
require 'open-uri'
kittens = open('http://placekitten.com/200/300')

f = File.open('kittens.jpg', 'w')  # open file for writing. 'w' is a 2nd argument specifies how the file will be opened.
kittens.each do |kitten|           # write selected kittens to the file
  f.write(kitten)
end

f.close

How to Open Files in Ruby

In the exaple above, we used a 2nd argument ‘w’ to open a file. This means open a file write-only (if the file exists, overwrites everything in the file). Other often used arguments are:

  1. r – read-only (starts at beginning of file)
  2. w+ – read and write (if the file exists, overwrites everything in the file)
  3. a+ – read and write (if the file exists, start at end of file. Otherwise creates a new file)

More on opening, reading and writing files in Ruby on LaunchSchool
More on opening, reading and writing files in Ruby on CodeCademy

Make HTTP Request

require 'open-uri'
kittens = open('http://placekitten.com') # open the http://placekitten.com/ url for reading!
body = kittens.read[559, 441]            # read is where the GET request happens. read lines you need from a file!
puts body                                # puts the response

HTTP Methods:

  1. GET retrieves information from the specified source
  2. POST sends new information to the specified source
  3. PUT updates existing information of the specified source
  4. DELETE removes existing information from the specified source

HTTP Methods Examples:

  1. GET you type in an URL in your browser or click on a link
  2. POST you fill in and send a contact form on a website
  3. PUT you edit your blog post and save the new version
  4. DELETE you delete your previous tweet

Anatomy of an HTTP Request:

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

Typical (POST) HTTP Request example:

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

The HTTP request starts with the line which specifies:

#request method # requested document # HTTP version

For instance:

GET /womenwhocode.ru/http-methods HTTP/1.1

Endpoints

Endpoints are API-defined locations where particular data is stored. For instance, you can GET a particular tweet from Twitter, or a particular bag from Amazon, or endpoints for the most popular/most recent videos or videos belonging to a certail genre or category, if you’re using the API for a video hosting service.

Authentication & API Keys

Typical API key example:

api_key = "FtHwuH8w1RDjQpOr0y0gF3AWm8sRsRzncK3hHh9"

HTTP Status Code

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 contains a 3-digit status code, that can start 1, 2, 3, 4, 5. Each set of codes has a specific meaning:

  1. 1xx – informational responses
  2. 2xx – success
  3. 3xx – redirection
  4. 4xx – client errors
  5. 5xx – server errors
Understanding HTTP Status Codes:
  1. 1xx – “Got it! I’m working on your request” (rare)
  2. 2xx – “Success!” – the server sends it when it’s successfully responding to your request
  3. 3xx – “I can do what you want, but I have to do something else first” – You’ll see this if the server have to reroute your request to another address to get you the resource you asked for
  4. 4xx – “You probably made a mistake!”
  5. 5xx – “The server goofed up and can’t successfully respond to your request”
Example of calling a status code returned by the server:
require 'open-uri'
placekitten = open('http://placekitten.com/')
# Puts placekitten status code returned by the server
puts placekitten.status
# => 200 OK

HTTP Response Anatomy

The HTTP response structure mirrors that of the HTTP request:

  • response line includes a three-digit HTTP status code
  • header includes further information about the server and its response
  • body contains the text of the response

HTTP Response example:

HTTP/1.1 200 OK                         # response line
Content-Type: text/xml; charset=UTF-8   # header

Accepted

Parsing XML

XML = EXtensible Markup Language. XML is very similar to HTML, the difference – XML allows to use tags that you make up instead of the W3C tags:


  Jeffrey
  Giraffe

Parsing XML example:
require "rexml/document"          # require module for parsing XML
file = File.open("pets.txt")      # read file pets.txt
doc = REXML::Document.new file
file.close
doc.elements.each("pets/pet/name") do |element|
  puts element
end
# result: => Jeffrey
Gustav
Gregory
[ ... ,  ... ,  ... ]

Parsing JSON

JSON = JavaScript Object Notation. It resembles JS objects. In JSON data is organised in key-value pairs, just like in an Excel spreadsheet. And like in Excel you can ask for the data that’s in cell A-16, in JSON you can ask an array for the data under a specific key. For instance, if you want to know how many likes the fb page has, ask for the data contained under the key “likes” in the JSON array of an FB API. All metaprogramming languages will be able to incorporate this JSON response.

JSON example:
{
  "pets": {
    "name": "Jeffrey",
    "species": "Giraffe"
  }
}
Parsing JSON example:
require 'json'                       # require module for parsing JSON
pets = File.open("pets.txt", "r")
doc = ""
pets.each do |line|
  doc << line
end
pets.close
puts JSON.parse(doc)
# result: => {"pets"=>{"name"=>"Jeffrey", "species"=>"Giraffe"}}

To know, what type of data a particular API uses to send you data, read its documentation.

Rails request/response cycle

How the Rails request/response cycle works:

  1. When a user goes to a specific URL, browser makes an HTTP request, asking a Router for that page
  2. The Router (config/routes.rb) receives the request and calls the relevant controller to handle it (maps the URL to the correct controller and action to handle the request)
  3. Controller receives the request and passes it on to the corresponding Model (or the View if no Model is required)
  4. Model fetches requested objects from the database
  5. Controller passes Models to the View
  6. View renders a page in HTML (can also generate reponses in other formats, like JSON, XML, etc)
  7. Controller sends the HTML view back to the browser via Router, the page loads and the User sees it

Here is an example of a simple Rails request/response cycle that doesn’t use a Model:

rails-http-request-response-cycle

(picture from “Learn Ruby on Rails” course on Codecademy)

Here is a scheme of a Rails MVC request/response cycle that use a Model and a Database:

rails-mvc-request-response-cycle

(picture from “Ruby on Rails 5 Essential Training” course on Lynda)

Though often not showed (but implied) on the diagrams, Router always stands betwee browser and controller, both when the request and the response happens. And there are exactly the HTTP request and an HTTP response:

http-request-and-response-in-rails-mvc

(picture from this post)

Resources:

  1. The Http and the Web | Http Explained | Request-Response Cycle
  2. Learn how to use the Twitter API on Codecademy – short basic course

NOTE:
proceed with
– GET request
– URL parameters and structure

No Comments

Post a Comment