85
Orange Hill, Beograd TIHOMIR OPA ČIĆ RESTful API-centric Universe

RESTful API-centric Universe

Embed Size (px)

Citation preview

Page 1: RESTful API-centric Universe

Orange Hill, BeogradTIHOMIR OPAČIĆ

RESTful API-centric Universe

Page 2: RESTful API-centric Universe

https://leanpub.com/build-apis-you-wont-hate

Building APIs You Won’t Hate

PHIL STURGEON*

*founder of PyroCMS, Software Developer at Kapture

Page 3: RESTful API-centric Universe

Web Facing mobile

aplikacije

iOS, Android…

RESTful API-centric UniverseGDE SE KORISTI RESTful API?

Page 4: RESTful API-centric Universe

Javscript MVVM

Frameworks Angular JS, Ember, Backbone…

RESTful API-centric UniverseGDE SE KORISTI RESTful API?

Page 5: RESTful API-centric Universe

Google Glass API

https://developers.google.com/glass/v1/reference/

RESTful API-centric UniverseGDE SE KORISTI RESTful API?

Page 6: RESTful API-centric Universe

Tesla Model S REST API

http://docs.timdorr.apiary.io/

RESTful API-centric UniverseGDE SE KORISTI RESTful API?

Page 7: RESTful API-centric Universe

Code on Demand

Layered System

Client-ServerCacheableStatelessUniform

Interface

REpresentational State Transfer

RESTful API-centric UniverseŠTA JE TO REST?

Arhitekturni model definisan u šest principa:

1 2 3 4 5 6

Page 8: RESTful API-centric Universe

Uniformni interfejs definiše client-server komunikaciju na način da razdvaja ove dve celine (decoupling the architecture).

Ovo omogućava da se ove dve celine zasebno razvijaju.

Uniformni interfejs Uniform Interface1

RESTful API-centric UniverseŠTA JE TO REST?

Page 9: RESTful API-centric Universe

Nepostojanje stanja je osnovna odlika REST arhitekture.

Svaki zahtev i odgovor servera na zahtev su jedinstvene nezavisne transakcije.

Nepostojanje stanjaStateless2

RESTful API-centric UniverseŠTA JE TO REST?

Page 10: RESTful API-centric Universe

Klijent je slobodan da kešira podatke koje je primio kao odgovor servera, ukoliko server explicitno označi podatke da se mogu keširati.

Mogućnost keširanjaCacheable3

RESTful API-centric UniverseŠTA JE TO REST?

Page 11: RESTful API-centric Universe

U interakciji klijenta i servera klijent ne vodi računa o čuvanju podataka, doke serveri ne vode računa o user interfejsu ili stanju klijenta.

Klijent-Server Client-Server4

RESTful API-centric UniverseŠTA JE TO REST?

Page 12: RESTful API-centric Universe

Klijent nema načina da zna da li je povezan direktno na krajnji server. Ovaj princip omogućava skalabilnost servisa (load balancing, shared cache).

Slojeviti sistem Layered System5

RESTful API-centric UniverseŠTA JE TO REST?

Page 13: RESTful API-centric Universe

Server je u mogućnosti da privremeno proširi mogućnosti klijenta da obavi određenu funkcionalnost tako što će mu preneti kod potreban za tu akciju, u vidu apleta ili skripti.

Kod na zahtev Code on Demand6

RESTful API-centric UniverseŠTA JE TO REST?

Page 14: RESTful API-centric Universe

http://en.wikipedia.org/wiki/Representational_state_transfer

Servis koji se kreće u granicama REST principa naziva se RESTful servisom.

RESTful API-centric UniverseREST MODEL U WEB SERVISIMA

Page 15: RESTful API-centric Universe

Karakteristike RESTful API servisa:

RESTful API-centric UniverseREST MODEL U WEB SERVISIMA

• koristi base URI, npr. http://example.com/resources/ • koristi Internet Media Type za prenos podataka.

Najčešće JSON (ili XML, Atom, microformats, images...) • koristi HTTP metode (npr. GET, PUT, POST ili DELETE) • koristi hypertext linkove da predstavi stanje (state) • koristi hypertext linkove da predstavi resurse

Page 16: RESTful API-centric Universe

RESTful API-centric UniverseRESTful API SERVISI - PROBLEMI U PRAKSI

• Površni članci i knjige, često usmereni ka primeni na samo jednom framework-u

• Razvojni principi se često se mešaju sa SOAP RPC razvojnim principima

• Nedostatak standarda

Page 17: RESTful API-centric Universe

REST/SOAP razlike:

RESTful API-centric UniverseRESTful API SERVISI - PROBLEMI U PRAKSI

• REST je arhitekturni model, SOAP je protokol (Glavni razlog nedostatka standarda)

Page 18: RESTful API-centric Universe

REST/SOAP razlike:

RESTful API-centric UniverseRESTful API SERVISI - PROBLEMI U PRAKSI

REST koristi sledeće operacije HTTP protokola:

SOAP RPC programer birazvijao ovakve API metode:

• GET • POST • PUT • DELETE

• getUsers() • getNewUsersSince(SinceDate) • saveOrder(CID, PurchaseID)

Page 19: RESTful API-centric Universe

RESTful API PROGRAMIRANJE

Page 20: RESTful API-centric Universe

1 Dizajniranje baze podataka

RESTful API-centric UniverseBAZA PODATAKA

2 Popunjavanje baze podacima (Seeding)

Zašto je seeding bitan?

Page 21: RESTful API-centric Universe

Seeding

RESTful API-centric UniverseSEEDING

“The process of creating seeding scripts means you don’t need to waste time creating this manually over and over again.”

• Acceptance testing • Podaci pravih korisnika ostaju poverljivi • Ne kopiramo podatke sa live servera na razvojne platforme

Page 22: RESTful API-centric Universe

Programiranje Seeding skripti

Ušteda vremena potrebnogda se baza podataka popuni test podacima.

Page 23: RESTful API-centric Universe

Faker

RESTful API-centric UniverseSEEDING

https://github.com/fzaninotto/Faker

"Faker is a PHP library that generates fake data for you.Faker is heavily inspired by Perl's Data::Faker, and by ruby's Faker."

Page 24: RESTful API-centric Universe

FakerRESTful API-centric UniverseSEEDING

Primer:

<?

    $faker = Faker\Factory::create();

    for ($i = 0; $i < Config::get('seeding.users'); $i++) {        $user = User::create([            'name' => $faker->name,            'email' => $faker->email,            'active' => $i === 0 ? true : rand(0, 1),            'gender' => rand(0, 1) ? 'male' : 'female'        ]);    }

Page 25: RESTful API-centric Universe

Da li koristiti Random podatke za svaki Seeding proces?

RESTful API-centric UniverseSEEDING

Da li se Acceptance testovi oslanjaju na nepromenljive podatke u bazi?

Page 26: RESTful API-centric Universe

iSeed

RESTful API-centric UniverseSEEDING

https://github.com/orangehill/iseed

"Inverse seed generator (iSeed) is a Laravel 4 package that provides a method to generate a new seed file based on data from the existing database table."

Page 27: RESTful API-centric Universe

iSeedRESTful API-centric UniverseSEEDING

Primeri:

$ php artisan iseed users

<?

    \Iseed::generateSeed('users’);\Iseed::generateSeed(‘photos’);\Iseed::generateSeed(‘categories');

Page 28: RESTful API-centric Universe

Endpoints Planning

RESTful API-centric UniverseENDPOINTS

Kreiranje spiska CRUD (Create, Read, Update, Delete) tačaka (endpoints) za resurse vaše aplikacije

Page 29: RESTful API-centric Universe

Endpoints Planning

RESTful API-centric UniverseENDPOINTS

Users - Create - Read - Update - Delete - List (active, suspended) - Image

Posts - Create - Read - Update - Delete - List (approved, disapproved)

Page 30: RESTful API-centric Universe

Naming ConventionBest Practices

Page 31: RESTful API-centric Universe

GET resources

RESTful API-centric UniverseNAMING CONVENTIONS

•GET /users - Lista korisnika sa paginacijom •GET /users/X - Samo korisnik X. ID, hash, slug, username, ili neki

drugi podatak koji jedinstveno opisuje resurs •GET /users/X,Y,Z - Podaci o tri korisnika

•GET /users/X/posts - Svi postovi jednog korisnika •GET /users/X/posts/Y - Jedan post jednog korisnika (ili bolje

GET /posts/Y - Jedan post)

Sub-resources:

Page 32: RESTful API-centric Universe

DELETE resources

RESTful API-centric UniverseNAMING CONVENTIONS

•DELETE /posts/X - Briše jedan post •DELETE /posts/X,Y,Z - Briše više postova •DELETE /posts - Briše sve postove - opasan endpoint! •DELETE /posts/X/images - Briše sve slike vezane za jedan post

Page 33: RESTful API-centric Universe

POST vs PUT War

RESTful API-centric UniverseNAMING CONVENTIONS

Koristite POST ako ne znate tačnu lokaciju resursa.

Primer:

POST /articles HTTP/1.1 HTTP/1.1 201 Created Location: /articles/63636

Page 34: RESTful API-centric Universe

POST vs PUT War

RESTful API-centric UniverseNAMING CONVENTIONS

Sad kad znate tačnu lokaciju resursa koristite PUT da ga ažurirate.

Primer:

PUT /article/63636 HTTP/1.1

Page 35: RESTful API-centric Universe

Idempotencija i sigurnost HTTP metoda

RESTful API-centric UniverseNAMING CONVENTIONS

Sigurnim HTTP metodamase smatraju one koje ne menjaju resurs.

Idempotentnim HTTP metodama se smatraju one koje mogu da se pozivaju više puta,bez da se rezultat, ali ne obavezno i resurs, nakon poziva promeni. Na primer, možemo pokušati sa postavljanjem slike jednom ili više puta, u slučaju da postoji problem sa konekcijom.

Page 36: RESTful API-centric Universe

Idempotencija i sigurnost HTTP metoda

RESTful API-centric UniverseNAMING CONVENTIONS

Page 37: RESTful API-centric Universe

POST vs PUT War

RESTful API-centric UniverseNAMING CONVENTIONS

Zaključak:

PUT je idempotentna nesigurna metoda,dok POST nije ni jedno ni drugo.

Page 38: RESTful API-centric Universe

Endpoints Plural or Singular?

RESTful API-centric UniverseENDPOINTS - PLURAL OR SINGULAR?

Primer: GET /user/1 vraća jednom korisnika sa ID-em 1

Šta vraća GET /user - jednog ili više korisnika? Nejasno.

Page 39: RESTful API-centric Universe

Endpoints Plural or Singular?

RESTful API-centric UniverseENDPOINTS - PLURAL OR SINGULAR?

Možda da probamo: GET /user/1 odnosno GET /users

…ali šta je sa nepravilnim množinama engleskog jezika:GET /person/1 ili GET /people Zbunjujuće?

Page 40: RESTful API-centric Universe

Endpoints Plural or Singular?

RESTful API-centric UniverseENDPOINTS - PLURAL OR SINGULAR?

GET /users/1 GET /users GET /users/1/images

Množina kao rešenje:

Page 41: RESTful API-centric Universe

"1 Controller per Resource"

RESTful API-centric UniverseKONTROLERI

UsersController ImagesController PostsController

Page 42: RESTful API-centric Universe

JSON vs XML Output

Page 43: RESTful API-centric Universe

Prednosti JSONa nad XMLom:

RESTful API-centric UniverseJSON VS XML OUTPUT

• manja veličina fajla • XML ima problem sa čuvanjem tipa podataka

Svi moderni API servisi podržavaju JSON output.

Page 44: RESTful API-centric Universe

RESTful API-centric UniverseJSON VS XML OUTPUT

JSON:

{    "user": {        "id": 1,        "name": "Tihomir",        "active": true,        "image": null,        "empty_string": ""    }}

<users>    <user>        <id>1</id>        <name>Tihomir</name>        <active>1</active>        <image />        <empty_string />    </user></users>

<users>    <user id="1" active="1">        <name>Tihomir</name>        <image />        <empty_string />    </user></users>

XML: XML sa atributima:

Primeri prikaza tipa podataka:

Page 45: RESTful API-centric Universe

JSON API

Page 46: RESTful API-centric Universe

jsonapi.orgpreporuka formata

RESTful API-centric UniverseJSON API

Primer (tražimo jedan podatak):

{  "posts": [{    "id": "1",    "title": "Rails is Omakase"  }]}

Prednosti: Nedostaci:

•Konzistentnost • Pojedini frameworci se ne snalaze sa ovakvim outputom

•Zbunjujuće: Tražio sam jedan podatak a dobio kolekciju

Page 47: RESTful API-centric Universe

twitter.com APIRESTful API-centric UniverseJSON API

Primer (tražimo jedan podatak):

{    "name": "Tihomir Opacic",    "id": "500501255"}

Prednosti: Nedostaci:

•Minimalizam •Većina frameworka se snalazi

sa ovakvim outputom

• Nedostaje prostor za paginaciju i ostale meta podatke

{    "name": "John Galt",    "id": "1001"},{    "name": "Jack Harper",    "id": "1002"}

Primer (tražimo kolekciju):

Page 48: RESTful API-centric Universe

facebook.com APIRESTful API-centric UniverseJSON API

Primer (tražimo jedan podatak):

{    "name": "Tihomir Opacic",    "id": "500501255"}

Prednosti: Nedostaci:

•Minimalizam •Većina frameworka se snalazi

sa ovakvim outputom •Postoji prostor za paginaciju i

ostale meta podatke

• Nedostaje prostor za meta podatke u primeru zahtevanja jednog podatka

{    "data": [        {            "name": "John Galt",            "id": "1001"        },        {            "name": "Jack Harper",            "id": "1002"        }    ]}

Primer (tražimo kolekciju):

Page 49: RESTful API-centric Universe

Namespace Everything

RESTful API-centric UniverseJSON API

Primer (tražimo jedan podatak):

{    "data": {        "name": "Tihomir Opacic",        "id": "500501255"    }}

{    "data": [        {            "name": "John Galt",            "id": "1001"        },        {            "name": "Jack Harper",            "id": "1002"        }    ]}

Primer (tražimo kolekciju):

Page 50: RESTful API-centric Universe

Namespace Everything

RESTful API-centric UniverseJSON API

Primer (tražimo jedan podatak):

{    "data": {        "name": "Tihomir Opacic",        "id": "500501255"    }}

{    "data": [        {            "name": "John Galt",            "id": "1001"        },        {            "name": "Jack Harper",            "id": "1002"        }    ]}

Primer (tražimo kolekciju):

Page 51: RESTful API-centric Universe

Namespace Everything

RESTful API-centric UniverseJSON API

Primer (tražimo podatak o jednom korisniku, sa slikama):

{    "data": {        "name": "Tihomir"        "id": 1234,        "photos": {            "data": [                {                    "id": 111                    "url": "http://media.example.com/profile_large.jpg"                }            ]        }    }}

Page 52: RESTful API-centric Universe

HTTP Status Codes

RESTful API-centric UniverseSTATUS CODES

1xx is all about information (not used at all in APIs) 2xx is all about success 3xx is all about redirection 4xx is all about client errors 5xx is all about service errors

Page 53: RESTful API-centric Universe

HTTP Status Codes

Page 54: RESTful API-centric Universe

RESTful API-centric UniverseSTATUS CODES

Primer:(https://leanpub.com/build-apis-you-wont-hate)

200 - Generic everything is OK 201 - Created something OK 202 - Accepted but is being processed async (encoding a video, resizing image, etc) 400 - Bad Request (should really be for invalid syntax, but some folks use for validation) 401 - Unauthorized (no current user and there should be) 403 - The current user is forbidden from accessing this data 404 - That URL is not a valid route, or the item resource does not exist 410 - Data has been deleted, deactivated, suspended, etc 405 - Method Not Allowed (your framework will probably do this for you) 500 - Something unexpected happened and it is the APIs fault 503 - API is not here right now, please try again later

Page 55: RESTful API-centric Universe

RESTful API-centric Universe

Primer API greške:

{    "error": {        "type": "NotLoggedInException",        "message": "User session has expired at unix time 1385221367."    }}

STATUS CODES

Page 56: RESTful API-centric Universe

Typecasting"When building an API it is common for people to just grab stuff from the database and pass it to json_encode().”

Laravel: User::find(1)->toJson();

Page 57: RESTful API-centric Universe

RESTful API-centric UniverseTYPECASTING WITH FRACTAL

Često će baza podataka vratiti sve podatke tipa string,pa ćemo verovatno imati:

{    "user": {        "id": "1",        "name": "Tihomir",        "active": "1"    }}

{    "user": {        "id": 1,        "name": "Tihomir",        "active": true    }}UM

ESTO

Page 58: RESTful API-centric Universe

Fractal

RESTful API-centric UniverseTYPECASTING WITH FRACTAL

https://github.com/thephpleague/fractal

"Fractal provides a presentation and transformation layer for complex data output, the like found in RESTful APIs, and works really well with JSON.”

Page 59: RESTful API-centric Universe

Data RelationshipOverview of Methods

Page 60: RESTful API-centric Universe

Sub-Resources

RESTful API-centric UniverseDATA RELATIONSHIPS

Za svaki podresurs kreirati endpoint:

GET /users/X/posts

Nedostatak: Za svaki resurs potrebno je napraviti dodatni API pozivda bi dobili podresurs (1 + n).

Page 61: RESTful API-centric Universe

Compound Documents (Side-Loading)

RESTful API-centric UniverseDATA RELATIONSHIPS

Nedostatak: Ovakav API output često ostavlja previše posla programerima klijentske strane aplikacije.

{    "users": [        {            "id": 1,            "name": "Tihomir Opacic"        },        {            "id": 2,            "name": "John Galt"        }    ],  

"posts": [        {            "id": 1,            "author_id": 1,            "title": "Some Title",        },        {            "id": 2,            "author_id": 1,            "title": "Some Title",        },        {            "id": 3,            "author_id": 2,            "title": "Some Title",        }    ]}

Page 62: RESTful API-centric Universe

Embedded Documents (Nested-Loading)

RESTful API-centric UniverseDATA RELATIONSHIPS

GET /users?embedd=photos,posts{    "data": {        "name": "Tihomir"        "id": 1234,        "photos": {            "data": [                {                    "id": 111                    "url": “http://bit.ly/1.jpg"                }            ]        }

        "posts": {            "data": [                {                    "id": 111                    "title": "Post Title"                }            ]        }    }}

Generalno najfunkcionalniji od svih načina prikaza relacionih podataka.

Page 63: RESTful API-centric Universe

Embedded Documents with Fractal

RESTful API-centric UniverseDATA RELATIONSHIPS

https://github.com/thephpleague/fractal

Fractal je koristan i za kreiranje Nested-Loading API prikaza!

Page 64: RESTful API-centric Universe

RESTful API Testing

Page 65: RESTful API-centric Universe

Cucumber 

RESTful API-centric UniverseRESTFUL API TESTING

http://cukes.info/

Behat (BDD for PHP)http://behat.org/

Both use Gherkin(Domain-Specific Language)

http://docs.behat.org/guides/1.gherkin.html

Page 66: RESTful API-centric Universe

Gherkin

RESTful API-centric UniverseRESTFUL API TESTING

Primer API Outputa:

{    "user": {        "id": 1,        "name": "Tihomir"    }}

Feature:Places

Scenario:Finding a specific user    When I request "GET /users/1"    Then I get a "200" response    And scope into the "data" property        And the properties exist:            """            id            name            """        And the id property is an integer    And reset scope

Primer Gherkin testa:

Page 67: RESTful API-centric Universe

RESTful API Debugging

Page 68: RESTful API-centric Universe

POSTMAN

RESTful API-centric UniverseDEBUGGING

http://www.getpostman.com/

A powerful HTTP client to test web services. (A Chrome browser plugin)

Page 69: RESTful API-centric Universe

RESTful API-centric UniverseDEBUGGING

Page 70: RESTful API-centric Universe

Clockwork

RESTful API-centric UniverseDEBUGGING

https://github.com/itsgoingd/clockwork-chrome

"Clockwork is a Chrome extension for PHP development, extending Developer Tools with a new panel providing all kinds of information useful for debugging and profiling your PHP scripts."

Page 71: RESTful API-centric Universe

RESTful API-centric UniverseDEBUGGING

Page 72: RESTful API-centric Universe

RESTful API Authentication

Page 73: RESTful API-centric Universe

Standardna web aplikacija koristi sesije.

RESTful API-centric UniverseAUTHENTICATION

Restful API ne koristi sesije.

Page 74: RESTful API-centric Universe

Basic Authentication

RESTful API-centric UniverseAUTHENTICATION

Najlakši ali i najnesigurniji sistem za autentifikacije.

echo base64_decode(‘dGlob21pcjoxMjMxMjM=‘); // tihomir:123123

Authorization: Basic dGlob21pcjoxMjMxMjM=

Header:

PHP:

Page 75: RESTful API-centric Universe

Digest Authentication

RESTful API-centric UniverseAUTHENTICATION

Slično Basic autentifikaciji, nešto bezbedniji sistem jer koristi MD5 enkripciju, ali i dalje nebezbedan.

MD5... 4... 3... 2... 1... HACKED!

Page 76: RESTful API-centric Universe

OAuth 1.0a Authentication

RESTful API-centric UniverseAUTHENTICATION

Sa pojavom OAuth 2 prestao da bude popularan izbor.

Page 77: RESTful API-centric Universe

OAuth 2.0 Authentication

RESTful API-centric UniverseAUTHENTICATION

Da bi koristili OAuth 2.0 trebaće vam OAuth 2.0 Serverhttps://github.com/thephpleague/oauth2-server/

Proučite specifikacije OAuth 2.0 protokola:http://tools.ietf.org/html/draft-ietf-oauth-v2-23

Primer jednostavnog i sigurnog poziva:GET https://graph.facebook.com/me?access_token=DFGJKHDFGHDIFHG

Page 78: RESTful API-centric Universe

RESTful API Pagination

Page 79: RESTful API-centric Universe

RESTful API-centric UniversePAGINATION

{    "data": [        ...    ],    "pagination": {        "total": 1000,        "count": 12,        "per_page": 12,        "current_page": 1,        "total_pages": 84,        "next_url": "https://api.example.com/users?page=2&number=12"    }}

Problem #1: SELECT count(*);Problem #2: Ako se između dva HTTP zahteva u bazu dodaju novi podaci, isti podaci će biti prikazani dva puta.

Page 80: RESTful API-centric Universe

RESTful API-centric UniversePAGINATION

{    "data": [        ...    ],    "pagination": {        "cursors": {            "after": 12,            "next_url": "https://api.example.com/users?cursor=12&number=12"        }    }}

Offsets and Cursors

“Daj mi 12 podataka od podatka broj 12.”

Page 81: RESTful API-centric Universe

RESTful API Dokumentacija

Page 82: RESTful API-centric Universe

Swagger

RESTful API-centric UniverseDOKUMENTACIJA

https://helloreverb.com/developers/swagger

"Swagger™ is a specification and complete framework implementation for describing, producing, consuming, and visualizing RESTful web services.”

Page 83: RESTful API-centric Universe

RESTful API-centric UniverseDOKUMENTACIJA

Page 84: RESTful API-centric Universe

API Blueprint

RESTful API-centric UniverseDOKUMENTACIJA

http://apiary.io/blueprint

"API Blueprint is a documentation-oriented API description language.”

Page 85: RESTful API-centric Universe

We’re hiring!

www.orangehilldev.com

[email protected] +381.64.167.7367

Djordja Stanojevica 9b,11000 Belgrade, Serbia