Service approach for development Rest API in Symfony2

35
Service approach for development Rest API in Symfony2 Aleksey Kryvtsov @ Web-developer at CPCS [email protected]

Transcript of Service approach for development Rest API in Symfony2

Service approach for

development Rest API in

Symfony2Aleksey Kryvtsov @ Web-developer at CPCS

[email protected]

REST REpresentational State Transfer

PART 1

HISTORY

REST was defined by Roy Thomas Fielding in 2000

In his dissertation "Architectural Styles and the Design of Network - based Software Architectures"

3

● Client - server● Stateless● Cacheable● Layered system

● Uniform interface:○ Identification of resources○ Manipulation of resources through these representations○ Self-descriptive messages○ Hypermedia as the engine of application state (HATEOAS)

ARCHITECTURAL CONSTRAINTS

4

CLIENT - SERVER | STATELESS

5

CACHEABLE

Unsafe methods

Safe methods

GET /articles/1234 HTTP/1.1 - example of safe methodPUT /articles/1234 HTTP/1.1 - example of unsafe method

6

CACHING PROCESSGET /articles/1234 HTTP/1.1 - The resource is not cached yet - Send request to the API - Store response in cache and return

GET /articles/1234 HTTP/1.1 - The resource is cached - Return response from cache

PUT /articles/1234 HTTP/1.1 - Unsafe method, send to API

PURGE /articles/1234 HTTP/1.1 - API sends PURGE method to the cache - The resources is removed from the cache

GET /articles/1234 HTTP/1.1 - The resource is not cached yet - Send request to the API - Store response in cache and return

7

LAYERED SYSTEM

GET /article/1234 HTTP/1.1

8

Identification of resources

GET /article/1234 HTTP/1.1

9

Manipulation of resources through these representations

{"Title": "Your title", "Text": "Your text"}

{"id": 1, "Title": "Your title", "Text": "Your text"}

JSON

POST /articles HTTP/1.1

10

11

Self-descriptive messagesRequest:

GET /articles/1234 HTTP/1.1Host: test.host.comUser-Agent: Mozilla/5.0Accept: application/jsonConnection: close(empty line)

11

Server Response:

HTTP/1.1 200 OKDate: Wed, 16 Mar 2016 11:20:59 GMTServer: ApacheContent-Language: ruContent-Type: application/json; charset=utf-8Content-Length: 1234Connection: close(empty line)(json representation)

BENEFITS

● Reliability● Performance● Scalability● Simplicity● Portability● Modifiability● Visibility

12

REST design maturity levels (Richardson Maturity Model)

13

/index.php?controller=page&action=getarticleid=5

/article/5/4/6/size/media/image?page=2

Level 0

Cacheable ? Scalable ? Readable ? Simplicity ? Modifiability ? Visibility ?

14

GET /articles HTTP/1.1 We want all articles

GET /articles/5/photos/4/comments/1 HTTP/1.1We want the first comment of the fourth photo for the fifth article

GET /articles/5/photos/4/comments?page=1&limit=10 We want all comments of the fourth photo for the fifth article

Level 1 - Resources

15

GET, OPTIONS, HEAD

POST, PUT, PATCH, LINK, UNLINK

DELETE

Level 2 - HTTP verbs

16

Manipulation of Resources CRUD to HTTP verb mapping

Create = POST

Retrieve = GET

Update = PUT (or PATCH)

Delete = DELETE

17

Overview of (some) HTTP methodsHTTP Method Safe Idempotent

GET yes yes

HEAD yes yes

PUT no yes

POST no no

DELETE no yes

PATCH no no

18

HTTP Status Codes. Part IHTTP Code Message Description

200 OK The request was processed and returned successfully. Nothing was changed.

201 Created The new resource was created successfully

400 Bad Request Problem with the request, such as a missing, invalid or type mismatched parameter

401 Unauthorized The request did not have valid authorization credentials

403 Forbidden Private data you are not allowed to access, or you've hit a rate limit.

404 Not Found Your URL is wrong, or the requested resource doesn't exist

500 Server Error If this persists please contact support. We log and review all errors but your help often helps us fix it quicker.

19

HTTP Status Codes. Part II

Code range Message Description1xx Information 100 - Continue2xx Successful 201 - Created3xx Redirection 301 - Moved Permanently4xx Client Error 404 - Not Found5xx Server Error 501 - Not Implemented

20

POST /articles HTTP/1.1 { “title”: “Title” }

GET /articles/1 HTTP/1.1{ “id”: 1, “title”: “Title” }

PATCH /articles/1 HTTP/1.1{ “title”: “Title - 1” }

DELETE /articles/1 HTTP/1.1{ “message”: “Article was deleted” }

Example

21

Server Response:HTTP/1.1 201 Created

Response to a successful request

22

{ "id" : 12, "subject" : "I have a question!", "summary" : "Hi, ....", "customer" : { "name" : "Bob" }, "assignedUser": { "id" : 42, "name" : "Jim", // ...

Server Response:HTTP/1.1 500 Server ErrorServer: ApacheContent-Language: ruContent-Type: application/json; charset=utf-8

Errors: Useful error message

23

{ "code" : 1234, "message" : "Something bad happened :(", "description" : "More details about the error here", "documentation" : "http://somehost.api/errors/1234"}

Server Response:HTTP/1.1 400 Bad Request

Errors: Validation errors for PUT, PATCH and POST

24

{ "code" : 1024, "message" : "Validation Failed", "errors" : [ { "code" : 5432, "field" : "first_name", "message" : "First name cannot have fancy characters" }, { "code" : 5622, "field" : "password", "message" : "Password cannot be blank" } //...

An important concept developing the REST API is the Content Negotiation.

GET /api/v1/pages/10.html HTTP/1.1

GET /api/v1/pages/10.json HTTP/1.1

GET /api/v1/pages/10.xml HTTP/1.1

Content Negotiation

25

Content negotiation is a mechanism defined in the HTTP specification that makes it possible to serve different versions of a document (or more generally, a resource representation) at the same URI, so that user agents can specify which version fit their capabilities the best.

Content Negotiation. Definition

GET /api/v1/pages/10 HTTP/1.1

Accept: application/jsonAccept: application/xml

Accept: text/html26

The user agent provides an Accept HTTP header that lists acceptable media types and associated quality factors. The server is then able to supply the version of the resource that best fits the user agent's needs.

Content Negotiation. Quality factors

Accept: application/json; q=1.0, application/xml; q=0.8, text/html; q=0.6, text/*; q=0.1

27

HATEOAS - Hypermedia As The Engine Of Application State

Level 3 - Hypermedia Controls

The point of hypermedia controls is that they tell us what we can do next, and the URI of the resource we need to manipulate to do it.

● Use links to allow clients to discover locations and operations ● Link relations are used to express options ● Clients do not need to know URLs ● This controls the state

28

Level 3 - HATEOAS: Links and relations<articles>

<article> <id>1</id> <title>Title - 1</title> <link href="http://example.com/articles/1" rel="self" /> <link href="http://example.com/articles/1/catalogs" rel="catalogs" />

</article><article>

<id>2</id> <title>Title - 2</title> <link href="http://example.com/articles/2" rel="self" /> <link href="http://example.com/articles/2/catalogs" rel="catalogs" />

</article><link href="http://example.com/articles?page=1" rel="prev" /><link href="http://example.com/articles?page=2" rel="self" /><link href="http://example.com/articles?page=3" rel="next" />

</articles>

29

Level 3 - HATEOAS: Media typesThe second part is about adding media types to answer the question: What?. What is this resource? What does it contain or what do I need to create such a resource?

This part introduces your own content type:

Content-Type: application/vnd.yourname.something+xml

30

Level 3 - HATEOAS: Version First, you can add the version number in your URIs, this is the easy way:

/api/v1/users

You can use your new content type:

application/vnd.acme.pave-v1+xml

31

Development Rest API in Symfony232

To be continued...

Referenceshttps://ru.wikipedia.org/wiki/RESTWikihttp://restcookbook.comREST CookBookhttp://restful-api-design.readthedocs.org/en/latest/Thoughts on RESTful API Designhttp://www.crummy.com/writing/speaking/2008-QCon/act3.htmlLeonard Richardson The Maturity Heuristiсhttp://martinfowler.com/articles/richardsonMaturityModel.htmlRichardson Maturity Modelhttp://www.vinaysahni.com/best-practices-for-a-pragmatic-restful-apiBest Practices for Designing a Pragmatic RESTful API

34

Thank you

Questions ?Aleksey Kryvtsov [email protected]

35