Back to Home

Restful (Representational State Transfer) API

July 29, 2015

What is a RESTFUL API?

An API, or 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. For an API or web service to be RESTful, it must do the following:

  • Separate the client from the server
  • Not hold state between requests (meaning that 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)
  • Use HTTP and HTTP methods. The HTTP stands for HyperText Transfer Protocol. HyperText is text with links in it and a transfer protocol is a fancy way of saying "rules for getting something from one place to another." In this case, the rules are for transferring web pages to your browser. Use HTTPS is more secure way of communicating. Communications through an HTTPS server are encrypted by a secure certificate known as an SSL.
  • This is not an requirement but in general, API provide information in JSON format.
  • Making XML HTTP Request

    var xhr = new XMLHttpRequest(); xhr.open("GET", "https://www.codecademy.com/", false); xhr.setRequestHeader('Content-Type', 'text/xml'); //optional xhr.send(); //return from the server xmlDocument = xhr.responseXML; console.log(xmlDocument.childNodes['0'].textContent);

    The Four Verbs

    1. GET: retrieves information from the specified source (you just saw this one!)
    2. POST: sends new information to the specified source.
    3. PUT (or PATCH): updates existing information of the specified source.
    4. DELETE: removes existing information from the specified source.

    The Response Status Codes

    A Successful request to the server results in a response, which is the message the server sends back to you, the client.

    There are various status code but most important status is '200' status, which is okay. The most famous is '404' which is file not found. More detailed information about the status does are here

    HTTP Response structure mirrors that of the HTTP request. It contains, HTTP status code, a header and the body.