57
REST The right way

REST - The right way

Embed Size (px)

Citation preview

Page 1: REST - The right way

RESTThe right way

Page 2: REST - The right way

Quem sou?

Luís Santos - [email protected] @ SAPO - Portugal Telecom

Page 3: REST - The right way

Rest: O que é?

Page 4: REST - The right way

Rest: O que é?● Representational state transfer● Arquitectura● Baseada em HTTP● Principios

○ Client-Server○ Stateless○ Cacheable○ Layered System

Page 5: REST - The right way

Rest: Porquê?

Page 6: REST - The right way

Multiplataforma● Servidores

○ Todos os sistemas operativos e plataformas

● Clientes

○ Todas as plataformas (incluindo p. moveis)

Page 7: REST - The right way

Segurança● Confidencialidade dos dados

○ SSL

■ Destribuição de certificados

● Autenticação com certificados de cliente

Page 8: REST - The right way

Escalabilidade

● Escalabilidade horizontal○ Proxys○ Cache○ Load Balancer

Page 9: REST - The right way

Recursos

Page 10: REST - The right way

RecursosElementos de informação ou “registos” que podem usados através do seu URI (uniform resource identifier).

Exemplos:/api/books//api/books/9780199535569/

/api/books/9780199535569/authors

/api/authors//api/authors/123/

Page 11: REST - The right way

Verbos HTTPGET, POST, PUT, DELETE, HEAD, OPTIONS, PATCH(?)

Page 12: REST - The right way

Verbos: GETObter informação sobre um recurso. Este verbo não afecta o estado do recurso.

Verbo endpoint descrição

GET /api/books/ Lista todos os livros

GET /api/books/?limit=2&offset=10 Lista livros usando paginação

GET /api/books/author=John doe Pesquisa livros pelo nome do autor

GET /api/books/9780199535569/ Detalhes de um livro

Page 13: REST - The right way

Verbos: GETPedido

GET /api/books/?limit=2&offset=10

Resposta{

"total": 20,

"items": [

{

"isbn": "9780199535569",

"name": "Pride and Prejudice"

},

{

"isbn": "9780199535569",

"name": "Pride and Prejudice"

}

]

}

Page 14: REST - The right way

Verbos: GETPedido

GET /api/books/9780199535569/

RespostaHttp 1.1 200 OK{ "isbn" : "9780199535569", "name" : "Pride and Prejudice", "publication_date" : "2009” }

Page 15: REST - The right way

Verbos: POSTCria um novo recurso.

Verbo endpoint descrição

POST /api/books/ Adiciona um novo livro

Page 16: REST - The right way

Verbos: POSTPedido

POST /api/books/

{ "name" : "My Book" }

Resposta

Http 1.1 201 Created{ "isbn" : "9999999999991", "name" : "My Book" }

Page 17: REST - The right way

Verbos: PUTModifica ou adiciona um recurso expecifico.

Verbo endpoint descrição

PUT /api/books/9780199535569/ Altera ou adiciona o recurso

Page 18: REST - The right way

Verbos: PUTPedido

PUT /api/books/9999999999991/

{ "name" : "My Book 2" }

Resposta

{ "name" : "My Book 2" }

Page 19: REST - The right way

Verbos: DELETEApaga um recurso.

Verbo endpoint descrição

DELETE /api/books/9780199535569/ Apaga o recurso

Page 20: REST - The right way

Verbos: DELETEPedido

DELETE /api/books/9999999999991/

Resposta

Status 200

Page 21: REST - The right way

Verbos: HEADVerifica se um recurso existe.

Verbo endpoint descrição

HEAD /api/books/9780199535569/ Verifica se um recurso existe

Page 22: REST - The right way

Verbos: HEADPedido

HEAD /api/books/9780199535569/

Resposta

Status 200

Page 23: REST - The right way

Verbos: PATCHModifica parcialmente um recurso. http://www.rfc-editor.org/info/rfc5789 (Status: PROPOSED STANDARD)

Verbo endpoint descrição

PATCH /api/books/9780199535569/ Altera apenas algumas propriedades do recurso.

Page 24: REST - The right way

Verbos: PATCHPedido

PATCH /api/books/9780199535569/

{ "publication_date" : "2008” }

Resposta

{ "name" : "My Book 2", "publication_date" : "2008”}

Page 25: REST - The right way

Verbos: OPTIONS

Obtem metada sobre o recurso.

Page 26: REST - The right way

HTTP Status Code1xx, 2xx , 3xx, 4xx, 5xx

Page 27: REST - The right way

Http Status Code

Page 28: REST - The right way

Http Status Code

● 2xx - Sucesso● 4xx - Erro (Client side)● 5xx - Erro (Server side)

Page 29: REST - The right way

Http Status Code : Exemplos

● 200 Ok● 400 Bad Request● 404 Not Found● 401 Unauthorized● 403 Forbidden● 500 Internal Server Error

Page 30: REST - The right way

Error Handling

Page 31: REST - The right way

Error Handling

Page 32: REST - The right way

Error codes

● Usar sempre um código HTTP adequado● Códigos de erro categorizados● Mensagem de erro ● Link para a documentação● Identificador unico do pedido

○ Debug

Page 33: REST - The right way

Error codes

Certo{ "error": 1345 "message" : "Invalid ISBN code" "details" :"https://books.com/doc/errors/1345" “id” : 12398231987312}

Errado{ "error": 1345}

Page 34: REST - The right way

Cache

Page 35: REST - The right way

Cache

● Suporte para cache no protocolo● Server Cache vs Client Cache● Cache Headers

○ Cache-Control○ Last-Modified○ Etag

Page 36: REST - The right way

Cache: Client Cache (Cache-Control)

Page 37: REST - The right way

Cache: Client Cache (Last-Modified)

Page 38: REST - The right way

Cache: Client Cache (Etag)

Page 39: REST - The right way

Cache: Server Cache

Page 40: REST - The right way

Cache: Cache-Control● Cache-control: public

○ means the cached version can be saved by proxies and other intermediate servers, where everyone can see it.

● Cache-control: private ○ means the file is different for different users (such as their personal

homepage). The user’s private browser can cache it, but not public proxies.

● Cache-control: no-cache ○ means the file should not be cached. This is useful for things like

search results where the URL appears the same but the content may change.

Page 41: REST - The right way

Autenticação

Page 42: REST - The right way

Autenticação1. Utilização do header de autenticação. (Authorization)

● Basic Authentication○ Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=

● Custom Authentication Scheme (Amazon AWS)○ Authorization: AWS AKIAIOSFODNN7EXAMPLE:frJIUN8DYpKDtOLCwo//yllqDzg=

2. Utilização de certificado de cliente (SSL)

Page 43: REST - The right way

Content Type

Page 44: REST - The right way

Content Type

● JSON○ Performance○ Simplicidade○ Dynamic Language (PHP,JS)

● XML○ More tools○ More features○ Static language (Java,C#)

Page 45: REST - The right way

Content Type

Certo ErradoGET /api/books/9780199535569.json

GET /api/books/9780199535569.xml

GET /api/books/9780199535569?type=json

GET /api/books/9780199535569Accept: application/json

GET /api/books/9780199535569Accept: application/xml

GET /api/books/9780199535569Accept: application/epub+zip

Page 46: REST - The right way

Versionamento

Page 47: REST - The right way

Versionamento

Certo ErradoGET /api/v10/books/9780199535569 GET /api/books/9780199535569?v=10

GET /api/books/9780199535569X-API-Version : 10

Page 48: REST - The right way

Concorrência

Page 49: REST - The right way

Concorrência

Problema:2 clientes tentam modificar o recurso simultaneamente.Como garantir que as alterações não se sobrepõem?

Solução:Etag

Page 50: REST - The right way

Concorrência

Page 51: REST - The right way

WADLWeb Application Description Language

Page 52: REST - The right way

WADL

● “The Web Application Description Language (WADL) is a machine-readable XML description of HTTP-based web applications (typically REST web services).” - Wikipedia

● Semelhante ao WSDL

Page 53: REST - The right way

WADL<application xmlns="http://wadl.dev.java.net/2009/02"> <resources base="https://books.com/api"> <resource path="books"> <method name="GET">

<request> <param name="limit" required="false" default="30" style="query"/> <param name="offset" required="false" default="0" style="query"/> </request>

</method> <resource path="{isbn}"> <param required="true" style="template" name="isbn"/> <method name="GET"/> <method name="DELETE"/> </resource> </resource> </resources></application>

Page 54: REST - The right way

Outros

● Compressão “out of the box”○ Gzip

Page 55: REST - The right way

Hypermedia API

Page 56: REST - The right way
Page 57: REST - The right way

FIM