5. RESTful API – Titouan BENOIT
A Web service is a service offered by an electronic device to another one,
communicating with each other via the World wide web
– 2002: W3C Web Services Architecture Working Group
• SOAP (Simple Object Access Protocol)
• HTTP
• XML Serialization
– 2004: two major classes of Web services:
• REST-compliant Web services
• Arbitrary Web services
A software system designed to support interoperable machine-to-
machine interaction over a network
1. Introduction
RESTful API - v1.0 5
7. RESTful API – Titouan BENOIT
Representational State Transfer (REST)
– Software architectural style
– Communicate over (not always) HTTP(S)
– With HTTP verbs (GET, POST, PUT, DELETE, etc.)
– Web resources identified by Uniform Resource Identifiers (URIs)
– CRUD (Create, Read, Update, Delete)
– Examples:
• GET http://myapi.domain.com/resources/2
• DELETE http://myapi.domain.com/resources/3
• GET http://myapi.domain.com/resources
REST was defined by Roy Thomas Fielding in his 2000 PhD dissertation "Architectural Styles and the
Design of Network-based Software Architectures"
RESTful API - v1.0 7
2. RESTful API
9. RESTful API – Titouan BENOIT
RESTful API - v1.0 9
3. HTTP(S) Request
HTTP Verbs URI Action Description
GET api/resources getResourcesAction Retrieve all resources
GET api/resources/2 getResourceAction(id) Retrieve resource id 2
POST api/resources postResourcesAction(Request) Create a new resource
PATCH api/resources/1 patchResourcesAction(Request,id) Edit resource id 1
PUT api/resources/1 putResourcesAction(Request,id) Edit resource id 1
DELETE api/resources/3 deleteResourcesAction(id) Delete resource id 3
10. RESTful API – Titouan BENOIT
RESTful API - v1.0 10
3. HTTP(S) Request - Filters
Filters
– Filters and sorting on resources
• https://api.example.com/resources?filters=type1&sort=asc
– Only use URL parameters (GET vars) for filtering and sorting
15. RESTful API – Titouan BENOIT
Authentification
– No Auth
– Basic Auth
– Digest Auth
– OAuth 1.0
– Oauth 2.0
– AWS Signature
– …
We will see…
– Basic Auth
– Oauth 2.0
RESTful API - v1.0 15
5. Authentification
16. RESTful API – Titouan BENOIT
Basic Auth
– In request headers
• "Authorization": "Basic " + api_key
• api_key = btoa(username + ":" + password);
• Base64 encoding/decoding
Security note
– Server needs SSL layer! (http(s))
– Security is managed by the server
• Firewall
• User validation
• Response
• …
RESTful API - v1.0 16
5. Authentification – Basic Auth
JavaScript Example
HTTP Request
17. RESTful API – Titouan BENOIT
OAuth 2.0
Roles
– resource owner: generally yourself, the data owner
– resource server: server which hosts data
– client (application): an application which asks for data to the resource server
– authorization server: deliver tokens, this server can be the same as the resource
server
Tokens
– access_token
– refresh_token
Security note
– HTTPS ONLY!
RESTful API - v1.0 17
5. Authentification – OAuth 2.0 – 1/9
18. RESTful API – Titouan BENOIT
Client registration (on authorization server)
– Application Name
– Redirect URLs
– Grant Type(s)
– Example with Symfony2 as an OAuth2 server (FOSOAuthServerBundle):
• php app/console welp:oauth-server:client:create --redirect-uri="CLIENT_HOST" --grant-
type="authorization_code" --grant-type="password" --grant-type="refresh-token" --grant-
type="token" --grant-type="client_credentials"
– Response from the server:
• Client Id
• Client Secret
– RFC 6749 — Client Registration
RESTful API - v1.0 18
5. Authentification – OAuth 2.0 – 2/9
19. RESTful API – Titouan BENOIT
Grant Types
– Authorization Code Grant (authorization_code)
– Implicit Grant
– Resource Owner Password Credentials (password)
– Client Credentials (client_credentials)
RESTful API - v1.0 19
5. Authentification – OAuth 2.0 – 3/9
20. RESTful API – Titouan BENOIT
Authorization Code Grant (authorization_code)
RESTful API - v1.0 20
5. Authentification – OAuth 2.0 – 4/9
21. RESTful API – Titouan BENOIT
Implicit Grant (less secure)
RESTful API - v1.0 21
5. Authentification – OAuth 2.0 – 5/9
1. The client (JS App) wants to access to your
Facebook profil
2. You are redirected to the Facebook
authorization server.
3. If you autorized access, the authorization
server redirects you to the JS web app et
expose the token access in the url
throught a callback. Callback example:
http://example.com/oauthcallback#access
_token=MzJmNDc3M2VjMmQzN.
4. You can access to the Facebook API via
JavaScript with this access token (For
example:
https://graph.facebook.com/me?access_t
oken=MzJmNDc3M2VjMmQzN).
22. RESTful API – Titouan BENOIT
Resource Owner Password Credentials (password)
RESTful API - v1.0 22
5. Authentification – OAuth 2.0 – 6/9
We will
use this
23. RESTful API – Titouan BENOIT
Client Credentials (client_credentials)
RESTful API - v1.0 23
5. Authentification – OAuth 2.0 – 7/9
Here, the client application needs a
tierce service without a specific user
account.
For example, our application calls to
geoip API and it is authenticated via its
client credentials in order to access to
the service.
24. RESTful API – Titouan BENOIT
Use the access token
– Request parameters:
https://api.example.com/resources?access_token=MzJmNDc3M2VjMmQzN
– Header Authorization:
• GET /resources HTTP/1.1
Host: api.example.com
Authorization: Bearer MzJmNDc3M2VjMmQzN
RESTful API - v1.0 24
5. Authentification – OAuth 2.0 – 8/9
27. RESTful API – Titouan BENOIT
Guidelines
– 1°: URI as resources identifier
– 2°: HTTP verbs as operator identifier
– 3°: HTTP response as resources representation
– 4°: Authentification with a token
– 5°: Security = https
RESTful API - v1.0 27
6. Guidelines – 1/6
28. RESTful API – Titouan BENOIT
1°: URI as resources identifier
– List of resources
• NOK: https://api.example.com/resource
• OK: https://api.example.com/resources
– Filters and sorting on resources
• NOK: https://api.example.com/resources/filters/type1/sort/asc
• OK: https://api.example.com/resources?filters=type1&sort=asc
– Get a specific resource (id=5)
• NOK: https://api.example.com/resource/display/5
• OK: https://api.example.com/resources/5
– Get childs (relation) of a specific resource (id=5)
• NOK: https://api.example.com/resources/childs/5
• OK: https://api.example.com/resources/5/childs
– Get a specific child (id=46) (relation) of a specific resource (id=5)
• NOK: https://api.example.com/resources/childs/5/46
• OK: https://api.example.com/resources/5/childs/46
RESTful API - v1.0 28
6. Guidelines – 2/6
29. RESTful API – Titouan BENOIT
2°: HTTP verbs as operator identifier
– CRUD => POST: Create | GET: Read | PUT/PATCH: Update | DELETE: Delete
– Create a resource
• NOK: GET https://api.example.com/resources/create
• OK: POST https://api.example.com/resources
– Read/Get resource
• NOK: GET https://api.example.com/resources/display/98
• OK: GET https://api.example.com/resources/98
– Update resource
• NOK: POST https://api.example.com/resources/update/98
• OK: PUT https://api.example.com/resources/98
• OK: PATCH https://api.example.com/resources/98
– Delete resource
• NOK: GET https://api.example.com/resources/delete/98
• OK: DELETE https://api.example.com/resources/98
RESTful API - v1.0 29
6. Guidelines – 3/6
30. RESTful API – Titouan BENOIT
3°: HTTP response as resources representation
– HTTP response:
• HTTP code status
– 2xx
– 4xx
– 5xx
• Data structure
– JSON
– XML
– (HTML, CSV, …) less used
– Data response represents the resource
RESTful API - v1.0 30
6. Guidelines – 4/6
31. RESTful API – Titouan BENOIT
4°: Authentification with a token
– Basic Auth
• api_token = btoa(username + ":" + password);
• In request Header "Authorization": "Basic " + api_token
– OAuth2.0
• Request parameters:
https://api.example.com/resources?access_token=MzJmNDc3M2VjMmQzN
• Header Authorization:
– GET /resources HTTP/1.1
Host: api.example.com
Authorization: Bearer MzJmNDc3M2VjMmQzN
RESTful API - v1.0 31
6. Guidelines – 5/6
32. RESTful API – Titouan BENOIT
5°: Security = https
– TLS/SSL layer + tierce certificate
• Encrypt data transmission
– Avoid leaks and attacks such as:
• Man in the middle
• Stealing packet and token
• …
RESTful API - v1.0 32
6. Guidelines – 6/6
37. RESTful API – Titouan BENOIT
Twitter REST APIs
– https://dev.twitter.com/rest/public
– Create a new App (https://apps.twitter.com/)
– Get Access Token
– Use the API!
RESTful API - v1.0 37
8. Examples – 1/6
HTTPS
HTTPS
38. RESTful API – Titouan BENOIT
Twitter REST APIs
– Using POSTMAN:
– [French] Nice PHP use case:
http://www.grafikart.fr/tutoriels/php/twitter-api-tweets-100
RESTful API - v1.0 38
8. Examples – 2/6
39. RESTful API – Titouan BENOIT
JSONPlaceholder
– http://jsonplaceholder.typicode.com/
– Fake Online REST API for Testing and Prototyping
– OpenSource:
• https://github.com/typicode/json-server
RESTful API - v1.0 39
8. Examples – 3/6
40. RESTful API – Titouan BENOIT
PublicAPIs
• https://www.publicapis.com/
• Web APIs directory (not all APIs are RESTful)
• You can add your API
RESTful API - v1.0 40
8. Examples – 4/6
41. RESTful API – Titouan BENOIT
Laravel REST API example
– https://github.com/Nightbr/jdn2014
– Basic Auth
– Request examples:
RESTful API - v1.0 41
8. Examples – 5/6
42. RESTful API – Titouan BENOIT
Symfony REST API example
– http://git.nbcorp.fr/oha/oha-api
– Basic Auth
– Using:
• FosRestBundle
• NelmioApiDoc
– Full project: http://blog.nbcorp.fr/2015/02/oha-open-home-
automation/
RESTful API - v1.0 42
8. Examples – 6/6
44. RESTful API – Titouan BENOIT
REST API with Laravel
– https://github.com/Nightbr/jdn2014/tree/master/app/api/laravel
– Routing (app/routes.php) [security Basic Auth]
RESTful API - v1.0 44
9. Development – Laravel - 1/6
45. RESTful API – Titouan BENOIT
REST API with Laravel
– Security Basic Auth (app/filters.php)
RESTful API - v1.0 45
9. Development – Laravel - 2/6
46. RESTful API – Titouan BENOIT
REST API with Laravel
– https://laravel.com/docs/5.1/controllers#restful-resource-controllers
– REST Controller (app/controllers/CategorieController.php)
RESTful API - v1.0 46
9. Development – Laravel - 3/6
47. RESTful API – Titouan BENOIT
REST API with Laravel
– REST Controller (app/controllers/CategorieController.php)
RESTful API - v1.0 47
9. Development – Laravel - 4/6
Exposed routes:
48. RESTful API – Titouan BENOIT
RESTful API - v1.0 48
9. Development – Laravel - 5/6
REST API with Laravel
– Laravel tips:
– View all app route:
• php artisan route
– Create database schema:
• php artisan migrate
– Add fixtures to database
• php artisan db:seed
– A nice admin panel for Laravel:
• http://administrator.frozennode.com/
– [French] REST API tutoriel with Laravel:
• http://www.grafikart.fr/tutoriels/php/rest-503
Laravel Administrator
49. RESTful API – Titouan BENOIT
RESTful API - v1.0 49
9. Development – Laravel - 6/6
REST API with Laravel
– Conclusion
• Lightweight RESTful API
• Very quick setup (2-4 hours max)
• Laravel framework (composer, artisan, …)
• Basic API
50. RESTful API – Titouan BENOIT
RESTful API - v1.0 50
9. Development – Symfony- 1/13
REST API with Symfony
– Usefull bundles
• FosRestBundle: https://github.com/FriendsOfSymfony/FOSRestBundle
• NelmioApiDoc: https://github.com/nelmio/NelmioApiDocBundle
– Based on http://swagger.io/
51. RESTful API – Titouan BENOIT
RESTful API - v1.0 51
9. Development – Symfony- 2/13
FosRestBundle
• Setup
– Install the bundle
» composer require friendsofsymfony/rest-bundle
– Enable the bundle
» app/AppKernel.php
» new FOSRestBundleFOSRestBundle(),
– Enable a Serializer
» JMSSerializerBundle
» composer require jms/serializer-bundle
» Register it in app/AppKernel.php
» new JMSSerializerBundleJMSSerializerBundle(),
52. RESTful API – Titouan BENOIT
RESTful API - v1.0 52
9. Development – Symfony- 3/13
FosRestBundle
– Configuration (app/config/config.yml)
– Routing (routing.yml)
– Routing (annotation in controller)
• use FOSRestBundleControllerAnnotations as Rest;
• * @RestGet("/needs/{id}/messages", requirements={"id": "d+"}, defaults={"_format":
"json"})
– Controller extends FOSRestController
53. RESTful API – Titouan BENOIT
RESTful API - v1.0 53
9. Development – Symfony- 4/13
FosRestBundle
– REST Controller: method
• getClientsAction() -> GET api.domain.com/v1/clients
• getClientAction($id) -> GET api.domain.com/v1/clients/{id}
• postClientsAction(Request $request) -> POST api.domain.com/v1/clients
• patchClientsAction(Request $request, $id) -> PATCH api.domain.com/v1/clients/{id}
• deleteClientsAction($id) -> DELETE api.domain.com/v1/clients/{id}
– Tips:
• use FOSRestBundleControllerAnnotations as Rest;
• In method annotation:
– * @RestView
– * @RestView(serializerEnableMaxDepthChecks=true)
54. RESTful API – Titouan BENOIT
RESTful API - v1.0 54
9. Development – Symfony- 5/13
FosRestBundle
use SensioBundleFrameworkExtraBundleConfigurationSecurity;
We use FosUserBundle to manage users, here is a constraint on user
Role. It is natively managed by Symfony Security Component
http://symfony.com/doc/current/book/security.html
Enable MaxDepthChecks of the Serializer is a necessary
optimisation for huge database. For example, if my client has
Many Testbenches and TestBench has modules and also clients, I
would like to retrieve only client’s Testbenches with my client
but no more than this. So in Entity/Client.php:
See NelmioApiDoc
55. RESTful API – Titouan BENOIT
RESTful API - v1.0 55
9. Development – Symfony- 6/13
FosRestBundle
56. RESTful API – Titouan BENOIT
RESTful API - v1.0 56
9. Development – Symfony- 7/13
FosRestBundle
57. RESTful API – Titouan BENOIT
RESTful API - v1.0 57
9. Development – Symfony- 8/13
FosRestBundle
– Filtering & sorting
• Use ParamFetcher
– use FOSRestBundleRequestParamFetcher;
• And QueryParam annotation:
– * @RestQueryParam(name=“limit", nullable=true)
– * @QueryParam(name=“sort", nullable=true, description=“asc/desc")
• And the controller: public function getTaskAction(ParamFetcher $paramFetcher)
{
foreach ($paramFetcher->all() as $criterionName => $criterionValue) {
// some logic here, eg building query
}
$results = // query database using criteria from above
// this is just a simple example how to return data
return new JsonResponse($results);
}
58. RESTful API – Titouan BENOIT
RESTful API - v1.0 58
9. Development – Symfony- 9/13
FosRestBundle
– Usefull links:
• http://symfony.com/doc/current/bundles/FOSRestBundle/index.html
• http://jmsyst.com/bundles/JMSSerializerBundle
• Add extra fields using JMSSerializer:
http://stackoverflow.com/questions/15007281/add-extra-fields-using-jms-
serializer-bundle
59. RESTful API – Titouan BENOIT
RESTful API - v1.0 59
9. Development – Symfony- 10/13
NelmioApiDoc
60. RESTful API – Titouan BENOIT
RESTful API - v1.0 60
9. Development – Symfony- 11/13
NelmioApiDoc
61. RESTful API – Titouan BENOIT
RESTful API - v1.0 61
9. Development – Symfony- 12/13
NelmioApiDoc
– composer require nelmio/api-doc-bundle
– Register the bundle in app/AppKernel.php
• new NelmioApiDocBundleNelmioApiDocBundle(),
– routing.yml
– app/config/config.yml
62. RESTful API – Titouan BENOIT
RESTful API - v1.0 62
9. Development – Symfony- 13/13
NelmioApiDoc
– In controller:
• use NelmioApiDocBundleAnnotationApiDoc;
• And add annotation to method:
– API Documention
• http://myapp/api/doc
• php app/console api:doc:dump --format=html > api.html --no-sandbox
– https://github.com/nelmio/NelmioApiDocBundle/blob/master/Resources/doc/index.md
64. RESTful API – Titouan BENOIT
RESTful API - v1.0 64
10. CORS – 1/3
CORS: CROSS-ORIGIN RESOURCE SHARING
– Cross-Origin Resource Sharing (CORS) is a specification that
enables truly open access across domain-boundaries. If you serve
public content, please consider using CORS to open it up for
universal JavaScript/browser access.
– http://enable-cors.org/index.html
– http://www.html5rocks.com/static/images/cors_server_flowchart
.png
65. RESTful API – Titouan BENOIT
RESTful API - v1.0 65
10. CORS – 2/3
CORS: CROSS-ORIGIN RESOURCE SHARING
– Server Side: CORS on PHP
– Client Side:
66. RESTful API – Titouan BENOIT
RESTful API - v1.0 66
10. CORS – 3/3
CORS: NelmioCorsBundle for Symfony2
– https://github.com/nelmio/NelmioCorsBundle
• Handles CORS preflight OPTIONS requests
• Adds CORS headers to your responses
– composer require nelmio/cors-bundle
– Register bundle
• new NelmioCorsBundleNelmioCorsBundle(),
– app/config/config.yml ->