RESTful API, nevidljiva spona koja spaja web-facing mobilne aplikacije sa online bazama podataka, server-side ishodište koje pokreće Javascript MVVM-based projekte često je nedovoljno istraženo područje čak i za iskusne programere. Ako vas zanima POST - PUT rat ili stvari poput idempotentnih nesigurnih metoda odgovore ćete pronaći u ovom predavanju.
Predavanje je održano 27. aprila 2014. godine u Beogradu na Google Code Day http://gcd.phpsrbija.rs/
2. PHIL STURGEON*
Building APIs
You Won’t Hate
https://leanpub.com/build-apis-you-wont-hate
*founder of PyroCMS, Software Developer at Kapture
3. GDE SE KORISTI RESTful API?
Web Facing
mobile
aplikacije
iOS, Android…
RESTful API-centric Universe
4. GDE SE KORISTI RESTful API?
Javscript
MVVM
Frameworks Angular JS,
Ember, Backbone…
RESTful API-centric Universe
5. GDE SE KORISTI RESTful API?
RESTful API-centric Universe
Google Glass
API
https://developers.google.com/glass/v1/reference/
6. GDE SE KORISTI RESTful API?
Tesla Model S
REST API
http://docs.timdorr.apiary.io/
RESTful API-centric Universe
7. 1 2 3 4 5 6
Code on
Demand
ŠTA JE TO REST?
RESTful API-centric Universe
REpresentational State Transfer
Layered
System
Arhitekturni model definisan u šest principa:
Client-
Stateless Cacheable Server Uniform
Interface
8. ŠTA JE TO REST?
RESTful API-centric Universe
Uniformni interfejs
1 Uniform Interface
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.
9. ŠTA JE TO REST?
RESTful API-centric Universe
Nepostojanje stanja
2 Stateless
Nepostojanje stanja je osnovna odlika REST
arhitekture.
Svaki zahtev i odgovor servera na zahtev su
jedinstvene nezavisne transakcije.
10. ŠTA JE TO REST?
RESTful API-centric Universe
Mogućnost keširanja
3 Cacheable
Klijent je slobodan da kešira podatke koje je
primio kao odgovor servera, ukoliko server
explicitno označi podatke da se mogu keširati.
11. ŠTA JE TO REST?
RESTful API-centric Universe
Klijent-Server
4 Client-Server
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.
12. ŠTA JE TO REST?
RESTful API-centric Universe
Slojeviti sistem
5 Layered System
Klijent nema načina da zna da li je povezan
direktno na krajnji server. Ovaj princip omogućava
skalabilnost servisa (load balancing, shared
cache).
13. ŠTA JE TO REST?
RESTful API-centric Universe
Kod na zahtev
6 Code on Demand
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.
14. REST MODEL U WEB SERVISIMA
RESTful API-centric Universe
Servis koji se kreće u
granicama REST principa
naziva se RESTful servisom.
http://en.wikipedia.org/wiki/Representational_state_transfer
15. REST MODEL U WEB SERVISIMA
RESTful API-centric Universe
Karakteristike
RESTful API servisa:
• 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
16. RESTful API SERVISI - PROBLEMI U PRAKSI
RESTful API-centric Universe
• 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
17. RESTful API SERVISI - PROBLEMI U PRAKSI
RESTful API-centric Universe
REST/SOAP razlike:
• REST je arhitekturni model, SOAP je protokol
(Glavni razlog nedostatka standarda)
18. RESTful API SERVISI - PROBLEMI U PRAKSI
RESTful API-centric Universe
REST/SOAP razlike:
REST koristi sledeće operacije
HTTP protokola:
SOAP RPC programer bi
razvijao ovakve API metode:
• GET
• POST
• PUT
• DELETE
• getUsers()
• getNewUsersSince(SinceDate)
• saveOrder(CID, PurchaseID)
20. BAZA PODATAKA
RESTful API-centric Universe
1 Dizajniranje baze podataka
2 Popunjavanje baze podacima
(Seeding)
Zašto je seeding bitan?
21. SEEDING
RESTful API-centric Universe
Seeding
“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
23. SEEDING
RESTful API-centric Universe
Faker
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."
25. SEEDING
RESTful API-centric Universe
Da li koristiti Random
podatke za svaki
Seeding proces?
Da li se Acceptance testovi
oslanjaju na nepromenljive podatke u bazi?
26. SEEDING
RESTful API-centric Universe
iSeed
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."
31. NAMING CONVENTIONS
RESTful API-centric Universe
GET resources
•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
Sub-resources:
•GET /users/X/posts - Svi postovi jednog korisnika •GET /users/X/posts/Y - Jedan post jednog korisnika (ili bolje
GET /posts/Y - Jedan post)
32. NAMING CONVENTIONS
RESTful API-centric Universe
DELETE resources
•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
33. NAMING CONVENTIONS
RESTful API-centric Universe
POST vs PUT War
Koristite POST ako ne znate tačnu lokaciju resursa.
Primer:
POST /articles HTTP/1.1
HTTP/1.1 201 Created Location: /articles/63636
34. NAMING CONVENTIONS
RESTful API-centric Universe
POST vs PUT War
Sad kad znate tačnu lokaciju resursa
koristite PUT da ga ažurirate.
Primer:
PUT /article/63636 HTTP/1.1
35. NAMING CONVENTIONS
RESTful API-centric Universe
Idempotencija i sigurnost
HTTP metoda
Sigurnim HTTP metodama
se 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.
37. NAMING CONVENTIONS
RESTful API-centric Universe
POST vs PUT War
Zaključak:
PUT je idempotentna nesigurna metoda,
dok POST nije ni jedno ni drugo.
38. ENDPOINTS - PLURAL OR SINGULAR?
RESTful API-centric Universe
Endpoints
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.
39. ENDPOINTS - PLURAL OR SINGULAR?
RESTful API-centric Universe
Endpoints
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?
40. ENDPOINTS - PLURAL OR SINGULAR?
RESTful API-centric Universe
Endpoints
Plural or Singular?
GET /users/1
GET /users
GET /users/1/images
Množina kao rešenje:
43. JSON VS XML OUTPUT
RESTful API-centric Universe
Prednosti JSONa nad XMLom:
• manja veličina fajla • XML ima problem sa čuvanjem tipa podataka
Svi moderni API servisi podržavaju JSON output.
46. jsonapi.org
preporuka formata
JSON API
RESTful API-centric Universe
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
47. JSON API
RESTful API-centric Universe twitter.com API
Primer (tražimo jedan podatak):
{
"name": "Tihomir Opacic",
"id": "500501255"
}
Primer (tražimo kolekciju):
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"
}
48. RESTful API-centric Universe facebook.com API
JSON API
Primer (tražimo jedan podatak):
{
"name": "Tihomir Opacic",
"id": "500501255"
}
Primer (tražimo kolekciju):
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"
}
]
}
51. Namespace
Everything
JSON API
RESTful API-centric Universe
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"
}
]
}
}
}
52. STATUS CODES
RESTful API-centric Universe
HTTP Status 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
54. STATUS CODES
RESTful API-centric Universe
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
55. STATUS CODES
RESTful API-centric Universe
Primer API greške:
{
"error": {
"type": "NotLoggedInException",
"message": "User session has expired at unix time 1385221367."
}
}
56. 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();
57. TYPECASTING WITH FRACTAL
RESTful API-centric Universe
Č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
}
UMESTO
}
58. TYPECASTING WITH FRACTAL
RESTful API-centric Universe
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.”
60. DATA RELATIONSHIPS
RESTful API-centric Universe
Sub-Resources
Za svaki podresurs kreirati endpoint:
GET /users/X/posts
Nedostatak:
Za svaki resurs potrebno je napraviti dodatni API poziv
da bi dobili podresurs (1 + n).
63. DATA RELATIONSHIPS
RESTful API-centric Universe
Embedded Documents
with Fractal
https://github.com/thephpleague/fractal
Fractal je koristan i za kreiranje Nested-Loading API prikaza!
65. RESTFUL API TESTING
RESTful API-centric Universe
Cucumber
http://cukes.info/
Behat (BDD for PHP)
http://behat.org/
Both use Gherkin
(Domain-Specific Language)
http://docs.behat.org/guides/1.gherkin.html
66. RESTFUL API TESTING
RESTful API-centric Universe
Gherkin
Primer API Outputa:
{
"user": {
"id": 1,
"name": "Tihomir"
}
}
Primer Gherkin testa:
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
70. DEBUGGING
RESTful API-centric Universe
Clockwork
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."
74. AUTHENTICATION
RESTful API-centric Universe
Basic Authentication
Najlakši ali i najnesigurniji sistem za autentifikacije.
Header:
Authorization: Basic dGlob21pcjoxMjMxMjM=
PHP:
echo base64_decode(‘dGlob21pcjoxMjMxMjM=‘); // tihomir:123123
75. AUTHENTICATION
RESTful API-centric Universe
Digest Authentication
Slično Basic autentifikaciji, nešto bezbedniji sistem jer koristi
MD5 enkripciju, ali i dalje nebezbedan.
MD5... 4... 3... 2... 1... HACKED!
77. AUTHENTICATION
RESTful API-centric Universe
OAuth 2.0 Authentication
Da bi koristili OAuth 2.0 trebaće vam OAuth 2.0 Server
https://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
79. PAGINATION
RESTful API-centric Universe
{
"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.
80. PAGINATION
RESTful API-centric Universe
Offsets and Cursors
{
"data": [
...
],
"pagination": {
"cursors": {
"after": 12,
"next_url": "https://api.example.com/users?cursor=12&number=12"
}
}
}
“Daj mi 12 podataka od podatka broj 12.”
82. DOKUMENTACIJA
RESTful API-centric Universe
Swagger
https://helloreverb.com/developers/swagger
"Swagger™ is a specification and complete framework
implementation for describing, producing, consuming, and
visualizing RESTful web services.”
84. DOKUMENTACIJA
RESTful API-centric Universe
API Blueprint
http://apiary.io/blueprint
"API Blueprint is a documentation-oriented API description
language.”