Understanding REST: Implementation

REST web APIs

A ReST web API is a web implementaion of principles of REST using HTTP. It is collection of resources, with defined facet:

  • the base URI for the API, such as http://www.iLearnStack.com/phonebook/UserDetails/
  • the internet media type of the data supported by the web API, such as JSON, XML
  • the set of operations supported by the API, such as GET, PUT, POST, DELETE ( known as request methods for HTTP)
  • the API must be hypertext driven

Considering a generic example, the standard output format of request methods can be consolidated as: 
    Resource: http://www.iLearnStack.com/phonebook/UserDetails/ (Collection URI)
        GET: List the details of addressed methods (in given scenario; UserDetails)
        PUT: Replace the enire addressed method with another addressed method
        POST: Create a new entry in the addressed method
        DELETE: Delete the entire addressed method

    Resource: http://www.iLearnStack.com/phonebook/UserDetails/12345
        GET: Retrieve the representation of the addressed member (in given scenario; 12345) of collection
        PUT: Replace the addressed member of the collection, or if it doesn’t exist, create it.
        POST: Not generally used. Treat the addressed member as a collection in its own right and create a new entry in it.
        DELETE: Delete the addressed member of the collection.

Using REST in Python

Issuing GET Requests

The Python module urllib2 is used to read URLs:

import urllib2
url = 'http://www.iLearnStack.com/phonebook/UserDetails/12345'
response = urllib2.urlopen(url).read()

Issuing POST Requests

A POST Request is simply passing request data as an encoded parameter to urlopen, hence:

import urllib2
import urllib
url = 'http://www.iLearnStack.com/phonebook/UserDetails/12345'
parameters = urllib.urlencode({
    'name': 'alpha',
    'surname;: 'beta'
    })
response = urllib2.urlopen(url, parameters).read()

REST: Openstack Implementaion

Getting Credentials

Credentials are a combination of user name, password, and what tenant (or project) cloud is running under. An additional token need to be generated if interacting with cloud directly with API endpoints, and not with a client. The Cloud administrator can provide a user name and a password as well as tenant identifier so that authorization tokens could be generated.
The tokens generated are typically good for 24 hours. The work flow goes like:

 

  • Begin API requests by asking for an authorization token from the endpoint your cloud administrator gave you. You send your user name, password, and what group or account you are with (the “tenant” in auth-speak).
curl -k -X 'POST' -v https://arm.trystack.org:5443/v2.0/tokens -d '{"auth":{"passwordCredentials":{"username": "joecool", "password":           "coolword"}, "tenantId":"5"}}' -H 'Content-type: application/json'
  • The server returns a response in which the 24-hours token is contained. Use that token to send API requests with the X-Auth-Token included as an header field.
curl -k -D - -H "X-Auth-Token: 7d2f63fd-4dcc-4752-8e9b-1d08f989cc00" -X 'GET' -v https://arm.trystack.org:9774/v1.1/296/extensions -H 'Content-type: application/json'
  • Repeatedly send API requests with that token in the X-Auth-Token header until either: 1) the job’s done or 2) you get a 401 (Unauthorized) code in return.
  • Request a token again when you get 401 (Unauthorized response) response.

Sending Requests to the API

A couple of options for sending requests to OpenStack through an API is available. Developers and testers may prefer to use cURL, the command-line tool. With cURL HTTP requests can be sent and responses are received back from the command line.

For a graphical interface, the REST client for Firefox also works well for testing and trying out commands.

Tokens need to be generated if cURL or a REST client are used.

Following example illustrates the curl commands that can check the list of servers.

curl -v -H "X-Auth-Token:tokengoeshere" http://127.0.0.1:8774/v2/tenantnnnnnn/servers

The output returned for the number of running servers looks like:

{
 "servers": [
        {
        "id": "server***",
        "links": [
                {
                "href": "http://127.0.0.1:8774/v2/tenantnnnnnn/servers/server***",
                 "rel": "self"
                 },
                {
               "href": "http://127.0.0.1:8774/tenantnnnnnn/servers/server***",
               "rel": "bookmark"
               }
                ],
           "name": "Test Server"
            }
            ]
}

For detailed APIs, available for Openstack this link can be referred to.

References

Learn REST

Openstack API start

Advertisements

Understanding REST : Basics

What is REST? 

Representational State Transfer (REST) is an architectural style for distributed systems such as the World Wide Web. The idea being, rather than using complex mechanisms to connect between machines, simple HTTP is used to make calls between machines.

REST is not a “standard”. And while there are REST programming frameworks, working with REST is so simple that you can often write own REST API’s with standard library features in languages like Perl, Java, or python.

Much like Web Services, a REST service is:

  • Platform-independent (you don’t care if the server is Unix, the client is a Mac, or anything else),
  • Language-independent (C# can talk to Java, etc.),
  • Standards-based (runs on top of HTTP), and
  • Can easily be used in the presence of firewalls.

Like Web Services, REST offers no built-in security features, encryption, session management, etc. But also as with Web Services, these can be added by building on top of HTTP:

  • For security, username/password tokens are often used.
  • For encryption, REST can be used on top of HTTPS (secure sockets).
  • … etc.

REST-style architectures consist of clients and servers. Clients initiate requests to servers while servers process requests and return appropriate responses. Requests and responses are built around the transfer of representations of resources. A resource can be essentially any coherent and meaningful concept that may be addressed. A representation of a resource is typically a document that captures the current or intended state of a resource.<1>

Constraints

There are two common perspectives on the process of architectural design, whether it be for buildings or for software. The first is that a designer starts with nothing and builds-up an architecture from familiar components until it satisfies the needs of the intended system. The second is that a designer starts with the system needs as a whole, without constraints, and then incrementally identifies and applies constraints to elements of the system in order to differentiate the design space and allow the forces that influence system behavior to flow naturally, in harmony with the system. Where the first emphasizes creativity and unbounded vision, the second emphasizes restraint and understanding of the system context. REST has been developed using the latter process and following ways would differentiate how these constraints are applied:

1. Client-server

 A uniform interface separates clients from servers. This separation of concerns means that, for example, clients are not concerned with data storage, which remains internal to each server, so that the portability of client code is improved. Servers are not concerned with the user interface or user state, so that servers can be simpler and more scalable. Servers and clients may also be replaced and developed independently, as long as the interface between them is not altered.

2 . Stateless

The client–server communication is further constrained by no client context being stored on the server between requests. Each request from any client contains all of the information necessary to service the request, and any session state is held in the client.

3. Cacheable

As on the World Wide Web, clients can cache responses. Responses must therefore, implicitly or explicitly, define themselves as cacheable, or not, to prevent clients reusing stale or inappropriate data in response to further requests. Well-managed caching partially or completely eliminates some client–server interactions, further improving scalability and performance.

4. Layered system

A client cannot ordinarily tell whether it is connected directly to the end server, or to an intermediary along the way. Intermediary servers may improve system scalability by enabling load-balancing and by providing shared caches. They may also enforce security policies.

5. Code-on-demand

Servers can temporarily extend or customize the functionality of a client by the transfer of executable code. Examples of this may include compiled components such as Java applets and client-side scripts such as JavaScript.

Complying with these constraints, and thus conforming to the REST architectural-style, enables any kind of distributed hypermedia system to have desirable properties, such as performance, scalability, simplicity, modifiability, visibility, portability, and reliability.

continued…

References:

Learn REST

Always a free source of knowledge

Fielding