http and rest apis

17
RESTful APIs... What, Why and How...

Upload: rahul-tanwani

Post on 18-Aug-2015

66 views

Category:

Technology


2 download

TRANSCRIPT

RESTful APIs... What, Why and How...

Web Application Architecture {MVC}

Presentation Layer

Business Layer

Data Access Layer(SQL or ORM)

DB

Takes care of Content Representation. (HTML5, CSS3).

Computational Logic on data using language libraries.

Access data from DB using RAW SQL queries or an ORM

Data Storage System (SQLite, MySQL, ORACLE).

Presentation Layer

Business Layer

Web and Mobile App - Sharing the same DB.

Data Access Layer(SQL or ORM)

DB

Presentation Layer

Business Layer

Data Access Layer(SQL or ORM)

Web App Mobile App

MySQL

Web - HTML5 & CSS3Mobile - Native GUI Libraries

Some part may repeat andsome may be unique.

Will be the same.

What's Different?

DRY - Do not Repeat Yourself

Lets combine the common logic into a single layer that both apps can leverage.

Web Service(s) Layer..

Presentation Layer

Business Layer

DB

MySQL

Presentation Layer

Web App Mobile App

Business Layer

HTTP Communication

(URLified)

Exposing data in the form of APIs.

Notes:

Data access logic and common business logic is segregated into a new layer.

Job of this layer is to get the data from data sources and expose it to applications.

To access data, applications make HTTP request to a particular URL, and gets back the required data as response.

WSL, can be thought of as an API driven SQL Engine, which in addition to expose data, allows applications to Create (Insert) new data into the system.

Web Service(s) Layer

So, What are web services anyway?

Web services can be thought of as web application that is intended to be used by Machines (Computers, Mobiles or any other device) as opposed to humans.

Philosophically, they can be described as Webified SQL engine, that allows client applications to make queries, insert new data, update or delete existing data.

Design Approaches:

Traditional Way - SOAP based web services (SOAP, WSDL, UDDI, WS*)

Today's Way - REST based APIs.

Web application intended to be used by machines.

Application consuming data through APIs.

How does this all fall into work?

Web Service(s) Layer

DB

MySQL

HTTP Request & Response

/v1/tasks

Json data

Presentation Logic

Data Management & May be some business logic.

HTTP

Various Applications

Single Data Access & Management layer.

Designing URL endpoints for our APIs

Requirement - Use Case Possible URL

To get all the tasks /v1/get-all-tasks

To get a particular task /v1/get-task/{id}

To create a task /v1/create-task

To delete a task /v1/delete-task/{id}

To update a task /v1/update-task/{id}

To get all tasks for a particular user /v1/get-tasks-for-users/{userId}

We may iterate over these APIs to see if we can improve...

Before understanding REST, lets design URI endpoints for an hypothetical application to track tasks and their associated users.

SO, What's REST?

Representational State Transfer. (You don't need to remember :) )In simple terms, server will return representation of state of the resource. Representation may include data in XML, JSON or any other format.

REST is resource oriented architecture. Everything revolves around resources.

What is resource? Resource is any entity that you may want to expose and that can be named. Typically, Each entity in ER-Diagram can be thought of as a resource.

In our application, we may have resources such as - Tasks and Users.

Don't worry, we shall see the practicals shortly.

REST guidelines (Principles)

2 URI's per resource. 1. Listing (collection) - /v1/tasks 2. Detail - /v1/tasks/{id}

Use nouns instead of verbs to name resources.So, instead of saying /v1/getAllTasks, we should say /v1/tasks.This means, we need to revise all our URIs to follow rest principles.

Prefer plurals over singular:/tasks over /task.

Huh..we might need to Redo our work... :(

Lets redesign our URI endpoints to follow REST principles.

For associations: /resource/{id}/resourceIn our case, we may have /user/8908/tasks, to get all the tasks for a user.

So, we are making progress in the right way now..

RESTified APIs (URL endpoints)...

Requirement - Use Case Possible URLs REST based URLs

To get all the tasks /v1/get-all-tasks /v1/tasks

To get a particular task /v1/get-task/{id} /v1/tasks/{id}

To create a task /v1/create-task/{id} /v1/tasks/

To delete a task /v1/delete-task/{id} /v1/tasks/{id}

To update a task /v1/update-task /v1/tasks/{id}

To get all tasks for a particular user

/v1/get-tasks-for-users/{userId}

/v1/users/{id}/tasks

Lets iterate over our APIs to see if we can apply REST principles on it..

How will the server know when to create, update or delete.. Lets find it out..

CRUD operations on REST APIs.

Telling server what action to perform..

HTTP provides request methods, that tells server what action to perform on a URI.

HTTP provides methods that can be directly mapped to RDBMS CRUD Operation. These methods include - GET, POST, PUT, DELETE.

Hmm..Lets see how our APIs should respond to these methods.

ResourcePOST

(Create)GET

(Read)PUT

(Update)DELETE(Delete)

/tasks Create a new task

Return all tasks

Replace all tasks with new tasks.

Delete all tasks

/tasks/123Create a task inside another

task.

Return a specific task

Update this task if exist or create a

new one.

Delete this task.

Responding to various HTTP methods..

Needs to be handled with care. (We may not implement them)

Well, this seems great..but how do applications come to know if their request succeeded or anything went wrong. (Specially for PUT and POST)?

Lets dig into HTTP to see if we can find an answer...

HTTP - Response Codes

Server sends response code for every client request. This communicates to clients what happened to the their request (Pass, fail, error etc). Response code for each type of request

Range (From client perspective)

Status code Method Comments.

1XX (100 - 199) * - Informational * Request is accepted and is in progress

2xx (200 - 299) - Success

200 - OK GET Request is served.

201 - Created POST / PUT

Whenever a server create new resource on client's request

202 - Accepted * Server accepted the requested but will be processed later.

204 - No Content

PUT Server performed the request but has no data to return.

Range (From client perspective)

Status code Method Comments.

3XX - Redirection 301 - Permanently moved

GET Server redirects client to the new URL of the same resource.

4xx (400 - 499) - Client Side Problem

400 - Bad Request.

* Client has used either wrong URL or parameters, or provided insufficient data in the request.

401 - Unauthorized.

* Client is unauthorized to make this request. (May be client have passed wrong credentials)

404 - Not Found GET The request resource cannot be found.

5xx (500 - 599) - Server Side Problem

500 - internal server error.

* Server has encountered some exception while serving the request.

HTTP - Response Codes (cont..)

What else can we expect from proper REST APIs?

Pagination:

Return subset of all the data present in DB. User must be able to tell you get me next 20 records after 60.

This can be achieved by adding offset and limit parameters to our GET APIs.ex. /v1/tasks?offset=60&limit=20

Multiple Representation Formats:

Server must return the data in more than one format (XML, JSON etc).

For client to specify what format the server should reply, ACCEPT http request header needs to be set. Ex. ACCEPT : Application/xml.

For server to specify what format is being used in the response format, Content-Type http response header needs to be set. Ex. Content-Type : Application/xml.

What else can we expect from proper REST APIs?(Cont..)

Filtering based on parameters:

Filtering acts as a WHERE clause in SQL statement. To get all tasks whose completion date is 1sy May 2013.

ex. /v1/tasks?completion-date=2013-05-01

Ordering:

This play a role of OrderBy clause in SQL statement. To get all the tasks sorted by priority.

ex. /v1/tasks?order_by=priority - Sorts in ascending order of priority.

/v1/tasks?order_by=-priority - Sorts in descending order of priority.

Lets see a quick demo to understand how we can implement REST APIs in django.

Thanks for listening :)

email - [email protected] - in.linkedin.com/in/tanwanirahulskype - tanwanirahul