Rest api titouan benoit
-
Upload
titouan-benoit -
Category
Software
-
view
586 -
download
2
Transcript of Rest api titouan benoit
RESTful API Titouan BENOIT – CTO at Welp.fr [email protected]
RESTful API – Titouan BENOIT
Titouan BENOIT – CTO at Welp – [email protected]
RESTful API - v1.0 2
Titouan BENOIT
Plan
RESTful API - v1.0 3
RESTful API – Titouan BENOIT
7. Tools – CURL
– Postman
8. Examples
9. Development – Laravel
– Symfony2
• FosRestBundle
• NelmioApiDoc
10. CORS – NelmioCors
1. Introduction
2. RESTful API
3. HTTP(S) Request
4. Response
– JSON – XML 5. Authentification
– Basic Auth – OAuth2 6. Guidelines
RESTFUL API
1. Introduction
4
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
RESTFUL API
2. RESTful API
6
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
RESTFUL API
3. HTTP(S) Request
8
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
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
RESTFUL API
4. Response
11
4. Response 1/2
– 1xx Informational – 2xx Success
• 200 OK
– 4xx Client Error • 400 Bad Request • 403 Forbidden • 404 Not Found
– 5xx Server Error • 500 Internal Server Error
http://www.restapitutorial.com/httpstatuscodes.html
– XML (eXtensible Markup Language) • Markup Validation with DTD • Old platforms or platforms which
needs validation • bulletProof Technology!
– JSON (JavaScript Object Notation) • Object • Easy to manipulate with JavaScript • Lightweight
RESTful API - v1.0 12
RESTful API – Titouan BENOIT
Data structures HTTP code status
RESTful API – Titouan BENOIT
RESTful API - v1.0 13
4. Response 2/2
XML response
JSON response
NB: data is in the body of the response
RESTFUL API
5. Authentification
14
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
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
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
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
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
RESTful API – Titouan BENOIT
Authorization Code Grant (authorization_code)
RESTful API - v1.0 20
5. Authentification – OAuth 2.0 – 4/9
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_token=MzJmNDc3M2VjMmQzN).
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
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.
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
RESTful API – Titouan BENOIT
Sources – http://oauth.net/2/
– http://tools.ietf.org/html/rfc6749
– http://tutorials.jenkov.com/oauth2/index.html
– http://www.bubblecode.net/fr/2013/03/10/comprendre-oauth2/
– https://github.com/FriendsOfSymfony/FOSOAuthServerBundle/blob/ma
ster/Resources/doc/index.md
RESTful API - v1.0 25
5. Authentification – OAuth 2.0 – 9/9
RESTFUL API
6. Guidelines
26
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
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
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
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
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
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
RESTFUL API
7. Tools
33
RESTful API – Titouan BENOIT
cURL
– http://curl.haxx.se/docs/manual.html
– CLI (Command-line Interface)
– sudo apt-get install curl php5-curl #linux debian based
– Example:
• curl -X GET -H "Authorization: Basic
dGhpcdqsdqsdqsdssdfsdfsdfsdfsdfsd==" -H "Cache-Control: no-
cache" 'http://connectedocelot.nbcorp.fr/api/devices'
RESTful API - v1.0 34
7. Tools – 1/2
RESTful API – Titouan BENOIT
POSTMAN
– https://www.getpostman.com/
RESTful API - v1.0 35
7. Tools – 2/2
RESTFUL API
8. Examples
36
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
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
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
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
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
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
RESTFUL API
9. Development
43
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
RESTful API – Titouan BENOIT
REST API with Laravel
– Security Basic Auth (app/filters.php)
RESTful API - v1.0 45
9. Development – Laravel - 2/6
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
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:
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
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
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/
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 FOS\RestBundle\FOSRestBundle(),
– Enable a Serializer
» JMSSerializerBundle
» composer require jms/serializer-bundle
» Register it in app/AppKernel.php
» new JMS\SerializerBundle\JMSSerializerBundle(),
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 FOS\RestBundle\Controller\Annotations as Rest;
• * @Rest\Get("/needs/{id}/messages", requirements={"id": "\d+"}, defaults={"_format":
"json"})
– Controller extends FOSRestController
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 FOS\RestBundle\Controller\Annotations as Rest;
• In method annotation:
– * @Rest\View
– * @Rest\View(serializerEnableMaxDepthChecks=true)
RESTful API – Titouan BENOIT
RESTful API - v1.0 54
9. Development – Symfony- 5/13
FosRestBundle use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security; 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
RESTful API – Titouan BENOIT
RESTful API - v1.0 55
9. Development – Symfony- 6/13
FosRestBundle
RESTful API – Titouan BENOIT
RESTful API - v1.0 56
9. Development – Symfony- 7/13
FosRestBundle
RESTful API – Titouan BENOIT
RESTful API - v1.0 57
9. Development – Symfony- 8/13
FosRestBundle – Filtering & sorting
• Use ParamFetcher
– use FOS\RestBundle\Request\ParamFetcher;
• And QueryParam annotation:
– * @Rest\QueryParam(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); }
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
RESTful API – Titouan BENOIT
RESTful API - v1.0 59
9. Development – Symfony- 10/13
NelmioApiDoc
RESTful API – Titouan BENOIT
RESTful API - v1.0 60
9. Development – Symfony- 11/13
NelmioApiDoc
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 Nelmio\ApiDocBundle\NelmioApiDocBundle(),
– routing.yml
– app/config/config.yml
RESTful API – Titouan BENOIT
RESTful API - v1.0 62
9. Development – Symfony- 13/13
NelmioApiDoc
– In controller:
• use Nelmio\ApiDocBundle\Annotation\ApiDoc;
• 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
RESTFUL API
10. CORS
63
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
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:
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 Nelmio\CorsBundle\NelmioCorsBundle(),
– app/config/config.yml ->
RESTful API – Titouan BENOIT
RESTfull API – http://blog.nicolashachet.com/niveaux/confirme/larchitecture-rest-expliquee-en-5-regles/
– https://en.wikipedia.org/wiki/Representational_state_transfer
– https://en.wikipedia.org/wiki/Web_service
– https://en.wikipedia.org/wiki/Transport_Layer_Security
– http://symfony.com/doc/current/bundles/FOSRestBundle/index.html
– http://jmsyst.com/bundles/JMSSerializerBundle
– http://stackoverflow.com/questions/15007281/add-extra-fields-using-jms-serializer-bundle
– http://www.restapitutorial.com/httpstatuscodes.html
– http://oauth.net/2/
– http://tools.ietf.org/html/rfc6749
– http://tutorials.jenkov.com/oauth2/index.html
– http://www.bubblecode.net/fr/2013/03/10/comprendre-oauth2/
– https://github.com/FriendsOfSymfony/FOSOAuthServerBundle/blob/master/Resources/doc/index.md
– http://curl.haxx.se/docs/manual.html
– https://www.getpostman.com/
– https://dev.twitter.com/rest/public
– https://apps.twitter.com/
– http://www.grafikart.fr/tutoriels/php/twitter-api-tweets-100
– http://jsonplaceholder.typicode.com/
– https://github.com/typicode/json-server
– https://github.com/Nightbr/jdn2014
– http://enable-cors.org/index.html
– https://github.com/nelmio/NelmioCorsBundle
RESTful API - v1.0 67
SOURCES