README.html 51.9 KB
Newer Older
Olivier Berger's avatar
Olivier Berger committed
1
2
<!DOCTYPE html>
<html lang="en">
3
<head>
Olivier Berger's avatar
Cleanup    
Olivier Berger committed
4
<!-- 2018-05-14 lun. 16:05 -->
Olivier Berger's avatar
Olivier Berger committed
5
6
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
7
<title>Todo-Backend example implementation with Symfony 4 and api-platform</title>
Olivier Berger's avatar
Olivier Berger committed
8
9
<meta name="generator" content="Org mode">
<meta name="author" content="Olivier Berger">
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
<script type="text/javascript">
/*
@licstart  The following is the entire license notice for the
JavaScript code in this tag.

Copyright (C) 2012-2013 Free Software Foundation, Inc.

The JavaScript code in this tag is free software: you can
redistribute it and/or modify it under the terms of the GNU
General Public License (GNU GPL) as published by the Free Software
Foundation, either version 3 of the License, or (at your option)
any later version.  The code is distributed WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE.  See the GNU GPL for more details.

As additional permission under GNU GPL version 3 section 7, you
may distribute non-source (e.g., minimized or compacted) forms of
that code without the copy of the GNU GPL normally required by
section 4, provided you include this license notice and a URL
through which recipients can access the Corresponding Source.


@licend  The above is the entire license notice
for the JavaScript code in this tag.
*/
<!--/*--><![CDATA[/*><!--*/
 function CodeHighlightOn(elem, id)
 {
   var target = document.getElementById(id);
   if(null != target) {
     elem.cacheClassElem = elem.className;
     elem.cacheClassTarget = target.className;
     target.className = "code-highlighted";
     elem.className   = "code-highlighted";
   }
 }
 function CodeHighlightOff(elem, id)
 {
   var target = document.getElementById(id);
   if(elem.cacheClassElem)
     elem.className = elem.cacheClassElem;
   if(elem.cacheClassTarget)
     target.className = elem.cacheClassTarget;
 }
/*]]>*///-->
</script>
</head>
<body>
<div id="content">
<h1 class="title">Todo-Backend example implementation with Symfony 4 and api-platform</h1>
<div id="table-of-contents">
<h2>Table of Contents</h2>
<div id="text-table-of-contents">
<ul>
Olivier Berger's avatar
Cleanup    
Olivier Berger committed
64
65
<li><a href="#org91af2cd">1. Testing it live</a></li>
<li><a href="#org2f58860">2. Test locally</a>
66
<ul>
Olivier Berger's avatar
Cleanup    
Olivier Berger committed
67
<li><a href="#org2d1f656">2.1. Passing TodoBackend tests</a></li>
68
69
</ul>
</li>
Olivier Berger's avatar
Cleanup    
Olivier Berger committed
70
71
<li><a href="#org95bd0f0">3. Motivation</a></li>
<li><a href="#orge699fef">4. How it was built</a>
72
<ul>
Olivier Berger's avatar
Cleanup    
Olivier Berger committed
73
74
75
76
<li><a href="#orgf3327a3">4.1. Initialisation of the project</a></li>
<li><a href="#org58f630c">4.2. Adding the model of the Todo application with Doctrine</a></li>
<li><a href="#orgc36f41c">4.3. Add API Platform</a></li>
<li><a href="#org32cb3cc">4.4. Tweaking compliance with the TodoBackend API</a>
77
<ul>
Olivier Berger's avatar
Cleanup    
Olivier Berger committed
78
79
80
81
82
83
84
<li><a href="#orgb98f4d3">4.4.1. Installing the test suite and running it</a></li>
<li><a href="#orge5cb4d9">4.4.2. Adding default value for completed attribute</a></li>
<li><a href="#org344d521">4.4.3. Adding DELETE on collection</a></li>
<li><a href="#orge048d8d">4.4.4. Changing default content-type produced to JSON</a></li>
<li><a href="#org2ac8cce">4.4.5. Adding an url property for the Todo items</a></li>
<li><a href="#org34d540a">4.4.6. Supporting PATCH request on Todo items</a></li>
<li><a href="#orgcdb1dc1">4.4.7. Fixing the order naming</a></li>
85
86
</ul>
</li>
Olivier Berger's avatar
Olivier Berger committed
87
88
</ul>
</li>
Olivier Berger's avatar
Cleanup    
Olivier Berger committed
89
<li><a href="#orgbd548b1">5. Deploying on heroku</a>
Olivier Berger's avatar
Olivier Berger committed
90
<ul>
Olivier Berger's avatar
Cleanup    
Olivier Berger committed
91
92
<li><a href="#org7997f8f">5.1. Support CORS</a></li>
<li><a href="#orgc7b167a">5.2. Tuning Heroku for REST API</a></li>
93
94
95
96
97
98
99
</ul>
</li>
</ul>
</div>
</div>
<p>
This repository contains a <a href="https://www.todobackend.com/">Todo-Backend</a> example implementation made
Olivier Berger's avatar
Olivier Berger committed
100
101
with Symfony 4 using the <a href="http://api-platform.com/">api-platform</a>
project.
102
</p>
Olivier Berger's avatar
Olivier Berger committed
103

Olivier Berger's avatar
Cleanup    
Olivier Berger committed
104
105
<div id="outline-container-org91af2cd" class="outline-2">
<h2 id="org91af2cd"><span class="section-number-2">1</span> Testing it live</h2>
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
<div class="outline-text-2" id="text-1">
<p>
You can see a working version at
<a href="https://still-ravine-70063.herokuapp.com/">https://still-ravine-70063.herokuapp.com/</a>.
</p>

<p>
It provides the following endpoints :
</p>
<ul class="org-ul">
<li><a href="https://still-ravine-70063.herokuapp.com/">https://still-ravine-70063.herokuapp.com/</a> which displays some
documentation for the API (executable with swagger)</li>
<li><a href="https://still-ravine-70063.herokuapp.com/todos">https://still-ravine-70063.herokuapp.com/todos</a> which is the API
endpoint</li>
</ul>

<p>
It can be tested with the Todo-Backend tools at
<a href="http://www.todobackend.com/">http://www.todobackend.com/</a> :
</p>
<ul class="org-ul">
<li>a JS client : <a href="http://www.todobackend.com/client/">http://www.todobackend.com/client/</a> : <a href="http://www.todobackend.com/client/index.html?https://still-ravine-70063.herokuapp.com/todos">http://www.todobackend.com/client/index.html?https://still-ravine-70063.herokuapp.com/todos</a></li>
<li>the todobackend test suite : <a href="http://www.todobackend.com/specs/index.html?https://still-ravine-70063.herokuapp.com/todos">http://www.todobackend.com/specs/index.html?https://still-ravine-70063.herokuapp.com/todos</a>.</li>
</ul>
</div>
</div>

Olivier Berger's avatar
Cleanup    
Olivier Berger committed
133
134
<div id="outline-container-org2f58860" class="outline-2">
<h2 id="org2f58860"><span class="section-number-2">2</span> Test locally</h2>
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
<div class="outline-text-2" id="text-2">
<p>
Clone the project's Git repo (see
<a href="https://gitlab.com/olberger/todobackend-symfony4">https://gitlab.com/olberger/todobackend-symfony4</a>), and start it on
port 8000, for instance :
</p>
<div class="org-src-container">
<pre class="src src-sh">php -S 127.0.0.1:8000 -t public
</pre>
</div>

<p>
Then connect to <a href="http://localhost:8000/">http://localhost:8000/</a> or
<a href="http://localhost:8000/todos">http://localhost:8000/todos</a> in your browser. The app serves HTML
if requested, which documents its use, giving example requests for use
with cURL for instance. RTFM ;-)
</p>

<p>
You can then check the compatibility with the TodoBackend test suite :
</p>
</div>

Olivier Berger's avatar
Cleanup    
Olivier Berger committed
158
159
<div id="outline-container-org2d1f656" class="outline-3">
<h3 id="org2d1f656"><span class="section-number-3">2.1</span> Passing TodoBackend tests</h3>
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
<div class="outline-text-3" id="text-2-1">
<p>
You can test for todo-backend API compliance, by cloning the
repository's code from <a href="https://github.com/TodoBackend/todo-backend-js-spec">https://github.com/TodoBackend/todo-backend-js-spec</a>.
</p>

<p>
You may then test using :
</p>

<div class="org-src-container">
<pre class="src src-sh"><span style="color: #483d8b;">cd</span> todo-backend-js-spec
php -S localhost:8080
</pre>
</div>

<p>
You can then connect to
<a href="http://localhost:8080/?http://127.0.0.1:8000/api/todos">http://localhost:8080/?http://127.0.0.1:8000/api/todos</a> in your browser.
</p>
</div>
</div>
</div>

Olivier Berger's avatar
Cleanup    
Olivier Berger committed
184
185
<div id="outline-container-org95bd0f0" class="outline-2">
<h2 id="org95bd0f0"><span class="section-number-2">3</span> Motivation</h2>
186
187
188
189
190
191
192
193
194
195
196
197
198
199
<div class="outline-text-2" id="text-3">
<p>
We've been devising the teaching materials for a class on Web apps
development, taught in PHP with Symfony.
</p>

<p>
I thought it would be great to illustrate the course with some ToDo
app which could be compared to other implementations, and found
the TodoBackend project.
</p>

<p>
Instead of just doing some implementation for our colleagues and
Olivier Berger's avatar
Olivier Berger committed
200
201
202
students, I thought I could as well do one that could be useful to
others. Also, this took me hours to find the most suitable ways to
make it work with Symfony 4 and api-pltform.
203
204
205
206
207
208
209
210
211
212
</p>

<p>
Note that there used to be
<a href="https://github.com/oegnus/symfony2-todobackend">https://github.com/oegnus/symfony2-todobackend</a> for an older variant of
Symfony, which I used for inspiration.
</p>
</div>
</div>

Olivier Berger's avatar
Cleanup    
Olivier Berger committed
213
214
<div id="outline-container-orge699fef" class="outline-2">
<h2 id="orge699fef"><span class="section-number-2">4</span> How it was built</h2>
215
216
217
218
<div class="outline-text-2" id="text-4">
<p>
Here are some very raw notes I took when implementing it.
</p>
Olivier Berger's avatar
Olivier Berger committed
219
220
221
222

<p>
At the time of writing, this works with <i>Symfony 4.0.9</i>.
</p>
223
224
</div>

Olivier Berger's avatar
Cleanup    
Olivier Berger committed
225
226
<div id="outline-container-orgf3327a3" class="outline-3">
<h3 id="orgf3327a3"><span class="section-number-3">4.1</span> Initialisation of the project</h3>
227
228
229
230
231
232
233
234
235
236
<div class="outline-text-3" id="text-4-1">
<p>
No need for full-fledged web app:
</p>

<div class="org-src-container">
<pre class="src src-sh">composer --no-ansi create-project symfony/skeleton todobackend-symfony4
</pre>
</div>

Olivier Berger's avatar
Olivier Berger committed
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
<pre class="example">
Installing symfony/skeleton (v4.0.6)
  - Installing symfony/skeleton (v4.0.6): Loading from cache
Created project in todobackend-symfony4
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 21 installs, 0 updates, 0 removals
  - Installing symfony/flex (v1.0.80): Loading from cache
  - Installing symfony/polyfill-mbstring (v1.8.0): Loading from cache
  - Installing symfony/console (v4.0.9): Loading from cache
  - Installing symfony/routing (v4.0.9): Loading from cache
  - Installing symfony/http-foundation (v4.0.9): Loading from cache
  - Installing symfony/yaml (v4.0.9): Loading from cache
  - Installing symfony/framework-bundle (v4.0.9): Loading from cache
  - Installing symfony/http-kernel (v4.0.9): Loading from cache
  - Installing symfony/event-dispatcher (v4.0.9): Loading from cache
  - Installing psr/log (1.0.2): Loading from cache
  - Installing symfony/debug (v4.0.9): Loading from cache
  - Installing symfony/finder (v4.0.9): Loading from cache
  - Installing symfony/filesystem (v4.0.9): Loading from cache
  - Installing psr/container (1.0.0): Loading from cache
  - Installing symfony/dependency-injection (v4.0.9): Loading from cache
  - Installing symfony/config (v4.0.9): Loading from cache
  - Installing psr/simple-cache (1.0.1): Loading from cache
  - Installing psr/cache (1.0.1): Loading from cache
  - Installing symfony/cache (v4.0.9): Loading from cache
  - Installing symfony/dotenv (v4.0.9): Loading from cache
Writing lock file
Generating autoload files
Symfony operations: 4 recipes (4fa98d7dbee89e614151a1249a8999f2)
=1.0): From github.com/symfony/recipes:master
=3.3): From github.com/symfony/recipes:master
=3.3): From github.com/symfony/recipes:master
=4.0): From github.com/symfony/recipes:master
Executing script cache:clear [OK]
Executing script assets:install --symlink --relative public [OK]

Some files may have been created or updated to configure your new packages.
Please review, edit and commit them: these files are yours.

              
 What's next? 
              

  * Run your application:
    1. Change to the project directory
    2. Execute the php -S 127.0.0.1:8000 -t public command;
    3. Browse to the http://localhost:8000/ URL.

       Quit the server with CTRL-C.
       Run composer require server --dev for a better web server.

  * Read the documentation at https://symfony.com/doc
</pre>
291
292

<p>
Olivier Berger's avatar
Olivier Berger committed
293
<i>Note you may do the same withouth the &#x2013;no-ansi, which is used here for documentation generation purposes.</i>
294
295
296
</p>

<p>
Olivier Berger's avatar
Olivier Berger committed
297
The generated project is testable with:
298
299
300
301
302
303
304
305
</p>
<div class="org-src-container">
<pre class="src src-sh"><span style="color: #483d8b;">cd</span> todobackend-symfony4/
php -S 127.0.0.1:8000 -t public
</pre>
</div>

<p>
Olivier Berger's avatar
Olivier Berger committed
306
Cf. <a href="http://127.0.0.1:8000">http://127.0.0.1:8000</a> for the default Symfony page.
307
308
309
310
</p>
</div>
</div>

Olivier Berger's avatar
Cleanup    
Olivier Berger committed
311
312
<div id="outline-container-org58f630c" class="outline-3">
<h3 id="org58f630c"><span class="section-number-3">4.2</span> Adding the model of the Todo application with Doctrine</h3>
313
314
<div class="outline-text-3" id="text-4-2">
<p>
Olivier Berger's avatar
Olivier Berger committed
315
316
Cf. <a href="https://symfony.com/doc/current/doctrine.html">https://symfony.com/doc/current/doctrine.html</a> for docs explaining
the following.
317
318
</p>

Olivier Berger's avatar
Olivier Berger committed
319
320
321
<ol class="org-ol">
<li><p>
add the <code>doctrine</code> flex recipe:
322
</p>
Olivier Berger's avatar
Olivier Berger committed
323
324
325
326
<div class="org-src-container">
<pre class="src src-sh">composer --no-ansi require doctrine
</pre>
</div>
327
328

<pre class="example">
Olivier Berger's avatar
Olivier Berger committed
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
Using version ^1.0 for symfony/orm-pack
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 20 installs, 0 updates, 0 removals
  - Installing ocramius/package-versions (1.3.0): Loading from cache
  - Installing zendframework/zend-eventmanager (3.2.1): Loading from cache
  - Installing zendframework/zend-code (3.3.0): Loading from cache
  - Installing ocramius/proxy-manager (2.2.0): Loading from cache
  - Installing doctrine/lexer (v1.0.1): Loading from cache
  - Installing doctrine/inflector (v1.3.0): Loading from cache
  - Installing doctrine/collections (v1.5.0): Loading from cache
  - Installing doctrine/cache (v1.7.1): Loading from cache
  - Installing doctrine/annotations (v1.6.0): Loading from cache
  - Installing doctrine/common (v2.8.1): Loading from cache
  - Installing doctrine/dbal (v2.7.1): Loading from cache
  - Installing doctrine/migrations (v1.7.2): Loading from cache
  - Installing symfony/doctrine-bridge (v4.0.9): Loading from cache
  - Installing doctrine/doctrine-cache-bundle (1.3.3): Loading from cache
  - Installing jdorn/sql-formatter (v1.2.17): Loading from cache
  - Installing doctrine/doctrine-bundle (1.9.1): Loading from cache
  - Installing doctrine/doctrine-migrations-bundle (v1.3.1): Loading from cache
  - Installing doctrine/instantiator (1.1.0): Loading from cache
  - Installing doctrine/orm (v2.6.1): Loading from cache
  - Installing symfony/orm-pack (v1.0.5): Loading from cache
Writing lock file
Generating autoload files
Symfony operations: 4 recipes (21343349407f11ef7a645912700137a4)
=1.0): From github.com/symfony/recipes:master
=1.3.3): From auto-generated recipe
=1.6): From github.com/symfony/recipes:master
=1.2): From github.com/symfony/recipes:master
ocramius/package-versions:  Generating version class...
ocramius/package-versions: ...done generating version class
Executing script cache:clear [OK]
Executing script assets:install --symlink --relative public [OK]

Some files may have been created or updated to configure your new packages.
Please review, edit and commit them: these files are yours.


 Database Configuration 


  * Modify your DATABASE_URL config in .env

  * Configure the driver (mysql) and
    server_version (5.7) in config/packages/doctrine.yaml
</pre></li>

<li><p>
As advised, change the <code>DATABASE_URL</code> config in the <code>.env</code> file
to use SQLite (see results in <a href=".env">.env</a>) :
</p>

<pre class="example" id="env-patch">
385
386
387
388
389
390
391
392
393
--- .env.dist	2018-05-04 15:43:28.616980415 +0200
+++ .env	2018-05-04 16:06:03.082486709 +0200
@@ -17,5 +17,5 @@
 # Format described at http://docs.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/configuration.html#connecting-using-a-url
 # For an SQLite database, use: "sqlite:///%kernel.project_dir%/var/data.db"
 # Configure your db driver and server_version in config/packages/doctrine.yaml
-DATABASE_URL=mysql://db_user:db_password@127.0.0.1:3306/db_name
+DATABASE_URL=sqlite:///%kernel.project_dir%/var/data.db
 ###&lt; doctrine/doctrine-bundle ###
Olivier Berger's avatar
Olivier Berger committed
394
</pre></li>
395

Olivier Berger's avatar
Olivier Berger committed
396
397
398
<li><p>
Then create the database :
</p>
399
<div class="org-src-container">
Olivier Berger's avatar
Olivier Berger committed
400
<pre class="src src-sh">bin/console --no-ansi doctrine:database:create
401
402
403
</pre>
</div>

Olivier Berger's avatar
Olivier Berger committed
404
405
406
407
408
409
410
<pre class="example">
Created database /home/olivier/git/gitlab.com/olberger/tests-todobackends/todobackend-symfony4/var/data.db for connection named default
</pre></li>

<li><p>
Then use the maker tool to add a <code>Todo</code> entity with its properties
to the application model:
411
</p>
Olivier Berger's avatar
Olivier Berger committed
412

413
<div class="org-src-container">
Olivier Berger's avatar
Olivier Berger committed
414
<pre class="src src-sh">composer --no-ansi require maker --dev
415
416
417
</pre>
</div>

Olivier Berger's avatar
Olivier Berger committed
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
<pre class="example">
Using version ^1.4 for symfony/maker-bundle
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 2 installs, 0 updates, 0 removals
  - Installing nikic/php-parser (v4.0.1): Loading from cache
  - Installing symfony/maker-bundle (v1.4.4): Loading from cache
Writing lock file
Generating autoload files
ocramius/package-versions:  Generating version class...
ocramius/package-versions: ...done generating version class
Symfony operations: 1 recipe (a7c0ed916d629e82dac70251050bc1f9)
=1.0): From github.com/symfony/recipes:master
Executing script cache:clear [OK]
Executing script assets:install --symlink --relative public [OK]

Some files may have been created or updated to configure your new packages.
Please review, edit and commit them: these files are yours.
</pre></li>

<li><p>
Then use the <i>maker</i> helper:
</p>
442
443
444
445
446
<div class="org-src-container">
<pre class="src src-sh">php bin/console make:entity
</pre>
</div>

Olivier Berger's avatar
Olivier Berger committed
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
<pre class="example">
Class name of the entity to create or update (e.g. FierceKangaroo):
&gt; Todo

created: src/Entity/Todo.php
created: src/Repository/TodoRepository.php

Entity generated! Now let's add some fields!
You can always add more fields later manually or by re-running this command.

New property name (press &lt;return&gt; to stop adding fields):
&gt; title

Field type (enter ? to see all types) [string]:
&gt; 

Field length [255]:
&gt; 

Can this field be null in the database (nullable) (yes/no) [no]:
&gt; 

updated: src/Entity/Todo.php

Add another property? Enter the property name (or press &lt;return&gt; to stop adding fields):
&gt; completed

Field type (enter ? to see all types) [string]:
&gt; boolean

Can this field be null in the database (nullable) (yes/no) [no]:
&gt; 

updated: src/Entity/Todo.php

Add another property? Enter the property name (or press &lt;return&gt; to stop adding fields):
&gt; order

[ERROR] Name "order" is a reserved word.                                                          

Add another property? Enter the property name (or press &lt;return&gt; to stop adding fields):
&gt; todo_order

Field type (enter ? to see all types) [string]:
&gt; integer

Can this field be null in the database (nullable) (yes/no) [no]:
&gt; 

updated: src/Entity/Todo.php

Add another property? Enter the property name (or press &lt;return&gt; to stop adding fields):
&gt; 

 Success! 

Next: When you're ready, create a migration with make:migration
</pre>
505
506

<p>
Olivier Berger's avatar
Olivier Berger committed
507
<i>Note that the <code>order</code> attribute isn't allowed by Doctrine, so we'll call it <code>todo_order</code> instead. Later, we'll adjust this so that the API recognizes it as <code>order</code> by changing getters and setters operations</i>
508
509
</p>

Olivier Berger's avatar
Olivier Berger committed
510
511
512
513
514
515
516
<p>
This generates a <code>src/Entity/Todo.php</code> file with the corresponding
<code>@ORM</code> annotations
</p></li>

<li>Apply the migrations :</li>
</ol>
517
518
519
520
521
522
523
524
525
526
527
528
529
<div class="org-src-container">
<pre class="src src-sh">composer require migrations
</pre>
</div>

<pre class="example">
bin/console make:migration
</pre>

<div class="org-src-container">
<pre class="src src-sh">php bin/console doctrine:migrations:migrate
</pre>
</div>
Olivier Berger's avatar
Olivier Berger committed
530
531
532
533

<p>
bin/console &#x2013;no-ansi doctrine:schema:update &#x2013;force
</p>
534
535
536
</div>
</div>

Olivier Berger's avatar
Cleanup    
Olivier Berger committed
537
538
<div id="outline-container-orgc36f41c" class="outline-3">
<h3 id="orgc36f41c"><span class="section-number-3">4.3</span> Add API Platform</h3>
539
<div class="outline-text-3" id="text-4-3">
Olivier Berger's avatar
Olivier Berger committed
540
541
<ol class="org-ol">
<li><p>
542
543
544
545
Install the <a href="https://api-platform.com/">api-platform</a> (<a href="https://github.com/api-platform/api-platform">https://github.com/api-platform/api-platform</a>)
</p>

<div class="org-src-container">
Olivier Berger's avatar
Olivier Berger committed
546
<pre class="src src-sh">composer --no-ansi req api
547
</pre>
Olivier Berger's avatar
Olivier Berger committed
548
549
</div></li>
</ol>
550
551

<pre class="example">
Olivier Berger's avatar
Cleanup    
Olivier Berger committed
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
Using version ^1.1 for api-platform/api-pack
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 21 installs, 0 updates, 0 removals
  - Installing symfony/translation (v4.0.9): Loading from cache
  - Installing symfony/validator (v4.0.9): Loading from cache
  - Installing twig/twig (v2.4.8): Loading from cache
  - Installing symfony/twig-bridge (v4.0.9): Loading from cache
  - Installing symfony/twig-bundle (v4.0.9): Loading from cache
  - Installing symfony/inflector (v4.0.9): Loading from cache
  - Installing symfony/property-access (v4.0.9): Loading from cache
  - Installing symfony/security (v4.0.9): Loading from cache
  - Installing symfony/security-bundle (v4.0.9): Loading from cache
  - Installing symfony/expression-language (v4.0.9): Loading from cache
  - Installing symfony/asset (v4.0.9): Loading from cache
  - Installing webmozart/assert (1.3.0): Loading from cache
  - Installing phpdocumentor/reflection-common (1.0.1): Loading from cache
  - Installing phpdocumentor/type-resolver (0.4.0): Loading from cache
  - Installing phpdocumentor/reflection-docblock (4.3.0): Loading from cache
  - Installing nelmio/cors-bundle (1.5.4): Loading from cache
  - Installing willdurand/negotiation (v2.3.1): Loading from cache
  - Installing symfony/serializer (v4.0.9): Loading from cache
  - Installing symfony/property-info (v4.0.9): Loading from cache
  - Installing api-platform/core (v2.2.5): Loading from cache
  - Installing api-platform/api-pack (1.1.0): Loading from cache
Writing lock file
Generating autoload files
ocramius/package-versions:  Generating version class...
ocramius/package-versions: ...done generating version class
Symfony operations: 5 recipes (4e65598197d35ac240a72e14b210a0df)
=3.3): From github.com/symfony/recipes:master
=3.3): From github.com/symfony/recipes:master
=3.3): From github.com/symfony/recipes:master
=1.5): From github.com/symfony/recipes:master
=2.1): From github.com/symfony/recipes:master
Executing script cache:clear [OK]
Executing script assets:install --symlink --relative public [OK]

Some files may have been created or updated to configure your new packages.
Please review, edit and commit them: these files are yours.
Olivier Berger's avatar
Olivier Berger committed
593
594
595
596
597
598
599
600
601
602
</pre>

<ol class="org-ol">
<li><p>
Then declare the <code>Todo</code> entities as to be handled through the API:
</p>

<pre class="example" id="todoapiressourceinitial-patch">
--- a/src/Entity/Todo.php
+++ b/src/Entity/Todo.php
603
@@ -4,8 +4,11 @@ namespace App\Entity;
Olivier Berger's avatar
Olivier Berger committed
604

605
 use Doctrine\ORM\Mapping as ORM;
Olivier Berger's avatar
Olivier Berger committed
606

607
608
609
610
611
612
613
614
+use ApiPlatform\Core\Annotation\ApiResource;
+
 /**
  * @ORM\Entity(repositoryClass="App\Repository\TodoRepository")
+ * @ApiResource
  */
 class Todo
 {
Olivier Berger's avatar
Olivier Berger committed
615
616
</pre></li>
</ol>
617
618

<p>
Olivier Berger's avatar
Olivier Berger committed
619
You may then test the API at: <a href="http://127.0.0.1:8000/api">http://127.0.0.1:8000/api</a> in your browser
620
621
</p>

Olivier Berger's avatar
Olivier Berger committed
622
623
624
625
626
627
628
629
<p>
Here's the JSON-LD produced by default on the empty database:
</p>
<div class="org-src-container">
<pre class="src src-sh">curl -s -X GET <span style="color: #8b2252;">"http://127.0.0.1:8000/api/todos"</span> -H  <span style="color: #8b2252;">"accept: application/ld+json"</span> | jq -M
</pre>
</div>

630
<pre class="example">
Olivier Berger's avatar
Olivier Berger committed
631
632
633
634
635
636
637
{
  "@context": "/api/contexts/Todo",
  "@id": "/api/todos",
  "@type": "hydra:Collection",
  "hydra:member": [],
  "hydra:totalItems": 0
}
638
</pre>
Olivier Berger's avatar
Olivier Berger committed
639
640
641
</div>
</div>

642

Olivier Berger's avatar
Cleanup    
Olivier Berger committed
643
644
<div id="outline-container-org32cb3cc" class="outline-3">
<h3 id="org32cb3cc"><span class="section-number-3">4.4</span> Tweaking compliance with the TodoBackend API</h3>
Olivier Berger's avatar
Olivier Berger committed
645
<div class="outline-text-3" id="text-4-4">
Olivier Berger's avatar
Olivier Berger committed
646
647
648
649
650
651
652
<p>
The goal will be to test that the test suite works, for instance with <a href="http://www.todobackend.com/specs/index.html?http://127.0.0.1:8000/api/todos">http://www.todobackend.com/specs/index.html?http://127.0.0.1:8000/api/todos</a>
</p>

<p>
But that requires CORS support, so we'll test locally first
</p>
Olivier Berger's avatar
Olivier Berger committed
653
</div>
654

Olivier Berger's avatar
Cleanup    
Olivier Berger committed
655
656
<div id="outline-container-orgb98f4d3" class="outline-4">
<h4 id="orgb98f4d3"><span class="section-number-4">4.4.1</span> Installing the test suite and running it</h4>
Olivier Berger's avatar
Olivier Berger committed
657
658
<div class="outline-text-4" id="text-4-4-1">
<p>
Olivier Berger's avatar
Cleanup    
Olivier Berger committed
659
See <a href="#org2d1f656">Passing TodoBackend tests</a> for instructions on how to run the test suite locally.
Olivier Berger's avatar
Olivier Berger committed
660
661
662
663
</p>
</div>
</div>

Olivier Berger's avatar
Cleanup    
Olivier Berger committed
664
665
<div id="outline-container-orge5cb4d9" class="outline-4">
<h4 id="orge5cb4d9"><span class="section-number-4">4.4.2</span> Adding default value for completed attribute</h4>
Olivier Berger's avatar
Olivier Berger committed
666
<div class="outline-text-4" id="text-4-4-2">
667
<p>
Olivier Berger's avatar
Olivier Berger committed
668
669
We'll change the default values of the <code>completed</code> and <code>todo_order</code>
attributes for newly created items:
670
671
</p>
<div class="org-src-container">
Olivier Berger's avatar
Olivier Berger committed
672
673
674
<pre class="src src-php"><span style="color: #a020f0;">private</span> <span style="color: #000000; background-color: #ffffff;">$</span><span style="color: #a0522d;">completed</span> = <span style="color: #008b8b;">false</span>;

<span style="color: #a020f0;">private</span> <span style="color: #000000; background-color: #ffffff;">$</span><span style="color: #a0522d;">todo_order</span> = 0;
675
676
677
</pre>
</div>
</div>
Olivier Berger's avatar
Olivier Berger committed
678
</div>
679

Olivier Berger's avatar
Cleanup    
Olivier Berger committed
680
681
<div id="outline-container-org344d521" class="outline-4">
<h4 id="org344d521"><span class="section-number-4">4.4.3</span> Adding DELETE on collection</h4>
Olivier Berger's avatar
Olivier Berger committed
682
<div class="outline-text-4" id="text-4-4-3">
683
684
685
686
<p>
The DELETE on the collection is added with a custom operation
handler <code>TodoDelete</code>, which uses a method of the <code>TodoRepository</code> :
</p>
Olivier Berger's avatar
Olivier Berger committed
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779

<p>
We'll add a custom operation handler for DELETE on collections,
following advice at
<a href="https://api-platform.com/docs/core/operations#recommended-method">https://api-platform.com/docs/core/operations#recommended-method</a> :
</p>

<ol class="org-ol">
<li><p>
Add a new method to the Todo Repository class which deletes all entries:
</p>

<div class="org-src-container">
<label class="org-src-name"><span class="listing-number">Listing 1: </span><code>src/Repository/TodoRepository.php</code></label><pre class="src src-php"><span style="color: #a020f0;">class</span> <span style="color: #228b22;">TodoRepository</span> <span style="color: #a020f0;">extends</span> <span style="color: #228b22;">ServiceEntityRepository</span>
{
   <span style="color: #b22222;">// </span><span style="color: #b22222;">...</span>
   <span style="color: #8b2252;">/**</span>
<span style="color: #8b2252;">     * Delete all instances of Todo</span>
<span style="color: #8b2252;">     * </span>
<span style="color: #8b2252;">     * </span><span style="color: #008b8b;">@return</span><span style="color: #8b2252;"> </span><span style="color: #228b22;">mixed</span><span style="color: #8b2252;">|\Doctrine\DBAL\Driver\Statement|</span><span style="color: #228b22;">array</span><span style="color: #8b2252;">|NULL</span>
<span style="color: #8b2252;">     */</span>
    <span style="color: #a020f0;">public</span> <span style="color: #a020f0;">function</span> <span style="color: #0000ff;">deleteAll</span>()
    {
        <span style="color: #000000; background-color: #ffffff;">$</span><span style="color: #a0522d;">isDeleted</span> = <span style="color: #000000; background-color: #ffffff;">$</span><span style="color: #008b8b;">this</span>-&gt;<span style="color: #000000; background-color: #ffffff;">createQueryBuilder</span>(<span style="color: #8b2252;">"todo"</span>)
            -&gt;<span style="color: #000000; background-color: #ffffff;">delete</span>()
            -&gt;<span style="color: #000000; background-color: #ffffff;">getQuery</span>()-&gt;<span style="color: #000000; background-color: #ffffff;">execute</span>();

        <span style="color: #a020f0;">return</span> <span style="color: #000000; background-color: #ffffff;">$</span><span style="color: #a0522d;">isDeleted</span>;
    }

}
</pre>
</div></li>

<li><div class="org-src-container">
<label class="org-src-name"><span class="listing-number">Listing 2: </span><code>src/Controller/TodoDelete.php</code></label><pre class="src src-php"><span style="color: #483d8b;">&lt;?php</span>
<span style="color: #b22222;">// </span><span style="color: #b22222;">src/Controller/TodoDelete.php</span>

<span style="color: #a020f0;">namespace</span> <span style="color: #228b22;">App\Controller</span>;

<span style="color: #a020f0;">use</span> <span style="color: #228b22;">App\Repository\TodoRepository</span>;

<span style="color: #a020f0;">use</span> <span style="color: #228b22;">App\Entity\Todo</span>;

<span style="color: #a020f0;">class</span> <span style="color: #228b22;">TodoDelete</span>
{
    <span style="color: #8b2252;">/**</span>
<span style="color: #8b2252;">     * </span><span style="color: #008b8b;">@var</span><span style="color: #8b2252;"> </span><span style="color: #8b2252;">TodoRepository</span><span style="color: #8b2252;"> used for deleting all items</span>
<span style="color: #8b2252;">     */</span>
    <span style="color: #a020f0;">private</span> <span style="color: #000000; background-color: #ffffff;">$</span><span style="color: #a0522d;">entityRepository</span>;

    <span style="color: #a020f0;">public</span> <span style="color: #a020f0;">function</span> <span style="color: #0000ff;">__construct</span>(<span style="color: #228b22;">TodoRepository</span> <span style="color: #000000; background-color: #ffffff;">$</span><span style="color: #a0522d;">entityRepository</span>)
    {
        <span style="color: #000000; background-color: #ffffff;">$</span><span style="color: #008b8b;">this</span>-&gt;<span style="color: #a0522d;">entityRepository</span> = <span style="color: #000000; background-color: #ffffff;">$</span><span style="color: #a0522d;">entityRepository</span>;
    }

    <span style="color: #a020f0;">public</span> <span style="color: #a020f0;">function</span> <span style="color: #0000ff;">__invoke</span>()
    {
        <span style="color: #a020f0;">if</span>( <span style="color: #000000; background-color: #ffffff;">$</span><span style="color: #008b8b;">this</span>-&gt;<span style="color: #a0522d;">entityRepository</span>-&gt;<span style="color: #000000; background-color: #ffffff;">deleteAll</span>() )
        {
            <span style="color: #a020f0;">return</span> <span style="color: #a020f0;">array</span>();
        }
    }
}
</pre>
</div></li>

<li><p>
Add the custom DELETE configuration for the <code>@ApiResource</code>
annotation of api-platform :
</p>

<div class="org-src-container">
<pre class="src src-php"><span style="color: #8b2252;">/** </span><span style="color: #008b8b;">@ApiResource</span><span style="color: #8b2252;">(collectionOperations={</span>
<span style="color: #8b2252;"> *     "get",</span>
<span style="color: #8b2252;"> *     "post",</span>
<span style="color: #8b2252;"> *     "delete"={</span>
<span style="color: #8b2252;"> *         "method"="DELETE",</span>
<span style="color: #8b2252;"> *         "path"="/todos",</span>
<span style="color: #8b2252;"> *         "controller"="App\Controller\TodoDelete",</span>
<span style="color: #8b2252;"> *     }</span>
<span style="color: #8b2252;"> *  })</span>
<span style="color: #8b2252;">...</span>
</pre>
</div>

<p>
<i>Note that you need to explicitely declare the default methods GET and POST that are necessary too, in addition to the new DELETE method, as in the example above.</i>
</p></li>
</ol>
</div>
</div>

Olivier Berger's avatar
Cleanup    
Olivier Berger committed
780
781
<div id="outline-container-orge048d8d" class="outline-4">
<h4 id="orge048d8d"><span class="section-number-4">4.4.4</span> Changing default content-type produced to JSON</h4>
Olivier Berger's avatar
Olivier Berger committed
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
<div class="outline-text-4" id="text-4-4-4">
<p>
The default behaviour of the api-platform API, when the collection
index is requested, is to respond with JSON-LD, like :
</p>
<pre class="example">
{
  "@context": "/api/contexts/Todo",
  "@id": "/api/todos",
  "@type": "hydra:Collection",
  "hydra:member": [],
  "hydra:totalItems": 0
}
</pre>

<p>
This leads to a problem with the API test suite, reporting something
like:
</p>
<pre class="example">
after a DELETE the api root responds to a GET with a JSON representation of an empty array

AssertionError: expected { Object (@context, @id, ...) } to deeply equal []
</pre>

<p>
We'll then change the default content-type, by modifying the formats
like the following in <code>config/packages/api_platform.yaml</code> so that
JSON is the default:
</p>
812
<div class="org-src-container">
Olivier Berger's avatar
Olivier Berger committed
813
814
815
816
817
818
<label class="org-src-name"><span class="listing-number">Listing 3: </span><code>config/packages/api_platform.yaml</code></label><pre class="src src-yaml"><span style="color: #a0522d;">api_platform</span>:
<span style="color: #b22222;">  ...</span>
  <span style="color: #a0522d;">formats</span>:
    <span style="color: #a0522d;">json</span>:     [<span style="color: #8b2252;">'application/json'</span>]
    <span style="color: #a0522d;">html</span>:     [<span style="color: #8b2252;">'text/html'</span>]
    <span style="color: #a0522d;">jsonld</span>:   [<span style="color: #8b2252;">'application/ld+json'</span>]
819
820
821
822
</pre>
</div>
</div>
</div>
Olivier Berger's avatar
Cleanup    
Olivier Berger committed
823
824
<div id="outline-container-org2ac8cce" class="outline-4">
<h4 id="org2ac8cce"><span class="section-number-4">4.4.5</span> Adding an url property for the Todo items</h4>
Olivier Berger's avatar
Olivier Berger committed
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
<div class="outline-text-4" id="text-4-4-5">
<p>
In the specs of the TodoBackend API, the JSON representation of Todo
items should include a <code>url</code> attribute, which point to the URI of the
resource, which is computed by the Router's URL generation method.
</p>

<p>
We'll then complement the normalization of the items to JSON by adding
a custom <code>ApiNormalizer</code> in <code>src/Serializer/ApiNormalizer</code>, following
the guidelines of
<a href="https://api-platform.com/docs/core/content-negotiation#writing-a-custom-normalizer">https://api-platform.com/docs/core/content-negotiation#writing-a-custom-normalizer</a>.
</p>

<p>
<i>Note that we don't apply instructions at <a href="https://api-platform.com/docs/core/serialization/#decorating-a-serializer-and-add-extra-data">https://api-platform.com/docs/core/serialization/#decorating-a-serializer-and-add-extra-data</a> since we care for JSON and not JSON-LD here.</i>
</p>

<p>
We do so by modifying <code>config/services.yaml</code> to add :
</p>

<div class="org-src-container">
<pre class="src src-yaml"><span style="color: #a0522d;">services</span>:
<span style="color: #b22222;">  ...</span>
  <span style="color: #a0522d;">'App\Serializer\ApiNormalizer'</span>:
      <span style="color: #a0522d;">arguments</span>:
        - <span style="color: #8b2252;">'@api_platform.serializer.normalizer.item'</span>
        - <span style="color: #8b2252;">'@router'</span>
</pre>
</div>

<p>
/This injects the Router argument that will be needed to generate the route's URL.
</p>

<p>
And we'readding the corresponding class in <code>src/Serializer/ApiNormalizer.php</code>
</p>
<div class="org-src-container">
<label class="org-src-name"><span class="listing-number">Listing 4: </span><code>src/Serializer/ApiNormalizer.php</code></label><pre class="src src-php"><span style="color: #483d8b;">&lt;?php</span>
<span style="color: #b22222;">// </span><span style="color: #b22222;">src/Serializer/ApiNormalizer</span>
<span style="color: #a020f0;">namespace</span> <span style="color: #228b22;">App\Serializer</span>;

<span style="color: #a020f0;">use</span> <span style="color: #228b22;">Symfony\Bundle\FrameworkBundle\Routing\Router</span>;
<span style="color: #a020f0;">use</span> <span style="color: #228b22;">Symfony\Component\Routing\Generator\UrlGeneratorInterface</span>;
<span style="color: #a020f0;">use</span> <span style="color: #228b22;">Symfony\Component\Serializer\Normalizer\DenormalizerInterface</span>;
<span style="color: #a020f0;">use</span> <span style="color: #228b22;">Symfony\Component\Serializer\Normalizer\NormalizerInterface</span>;
<span style="color: #a020f0;">use</span> <span style="color: #228b22;">Symfony\Component\Serializer\SerializerAwareInterface</span>;
<span style="color: #a020f0;">use</span> <span style="color: #228b22;">Symfony\Component\Serializer\SerializerInterface</span>;

<span style="color: #a020f0;">final</span> <span style="color: #a020f0;">class</span> <span style="color: #228b22;">ApiNormalizer</span> <span style="color: #a020f0;">implements</span> <span style="color: #228b22;">NormalizerInterface</span>, <span style="color: #228b22;">DenormalizerInterface</span>, <span style="color: #228b22;">SerializerAwareInterface</span>
{

    <span style="color: #a020f0;">private</span> <span style="color: #000000; background-color: #ffffff;">$</span><span style="color: #a0522d;">decorated</span>;

    <span style="color: #8b2252;">/**</span>
<span style="color: #8b2252;">     * </span><span style="color: #008b8b;">@var</span><span style="color: #8b2252;"> </span><span style="color: #8b2252;">Router</span><span style="color: #8b2252;"> injected to generate the URL from the path</span>
<span style="color: #8b2252;">     */</span>
    <span style="color: #a020f0;">private</span> <span style="color: #000000; background-color: #ffffff;">$</span><span style="color: #a0522d;">router</span>;

    <span style="color: #a020f0;">public</span> <span style="color: #a020f0;">function</span> <span style="color: #0000ff;">__construct</span>(<span style="color: #228b22;">NormalizerInterface</span> <span style="color: #000000; background-color: #ffffff;">$</span><span style="color: #a0522d;">decorated</span>, <span style="color: #228b22;">Router</span> <span style="color: #000000; background-color: #ffffff;">$</span><span style="color: #a0522d;">router</span>)
    {
        <span style="color: #a020f0;">if</span> (! <span style="color: #000000; background-color: #ffffff;">$</span><span style="color: #a0522d;">decorated</span> <span style="color: #a020f0;">instanceof</span> <span style="color: #228b22;">DenormalizerInterface</span>) {
            <span style="color: #a020f0;">throw</span> <span style="color: #a020f0;">new</span> <span style="color: #228b22;">\InvalidArgumentException</span>(sprintf(<span style="color: #8b2252;">'The decorated normalizer must implement the %s.'</span>, <span style="color: #008b8b;">DenormalizerInterface</span>::<span style="color: #008b8b;">class</span>));
        }

        <span style="color: #000000; background-color: #ffffff;">$</span><span style="color: #008b8b;">this</span>-&gt;<span style="color: #a0522d;">decorated</span> = <span style="color: #000000; background-color: #ffffff;">$</span><span style="color: #a0522d;">decorated</span>;

        <span style="color: #000000; background-color: #ffffff;">$</span><span style="color: #008b8b;">this</span>-&gt;<span style="color: #a0522d;">router</span> = <span style="color: #000000; background-color: #ffffff;">$</span><span style="color: #a0522d;">router</span>;
    }

    <span style="color: #a020f0;">public</span> <span style="color: #a020f0;">function</span> <span style="color: #0000ff;">supportsNormalization</span>(<span style="color: #000000; background-color: #ffffff;">$</span><span style="color: #a0522d;">data</span>, <span style="color: #000000; background-color: #ffffff;">$</span><span style="color: #a0522d;">format</span> = <span style="color: #008b8b;">null</span>)
    {
        <span style="color: #a020f0;">return</span> <span style="color: #000000; background-color: #ffffff;">$</span><span style="color: #008b8b;">this</span>-&gt;<span style="color: #a0522d;">decorated</span>-&gt;<span style="color: #000000; background-color: #ffffff;">supportsNormalization</span>(<span style="color: #000000; background-color: #ffffff;">$</span><span style="color: #a0522d;">data</span>, <span style="color: #000000; background-color: #ffffff;">$</span><span style="color: #a0522d;">format</span>);
    }

    <span style="color: #a020f0;">public</span> <span style="color: #a020f0;">function</span> <span style="color: #0000ff;">normalize</span>(<span style="color: #000000; background-color: #ffffff;">$</span><span style="color: #a0522d;">object</span>, <span style="color: #000000; background-color: #ffffff;">$</span><span style="color: #a0522d;">format</span> = <span style="color: #008b8b;">null</span>, <span style="color: #a020f0;">array</span> <span style="color: #000000; background-color: #ffffff;">$</span><span style="color: #a0522d;">context</span> = [])
    {
        <span style="color: #000000; background-color: #ffffff;">$</span><span style="color: #a0522d;">data</span> = <span style="color: #000000; background-color: #ffffff;">$</span><span style="color: #008b8b;">this</span>-&gt;<span style="color: #a0522d;">decorated</span>-&gt;<span style="color: #000000; background-color: #ffffff;">normalize</span>(<span style="color: #000000; background-color: #ffffff;">$</span><span style="color: #a0522d;">object</span>, <span style="color: #000000; background-color: #ffffff;">$</span><span style="color: #a0522d;">format</span>, <span style="color: #000000; background-color: #ffffff;">$</span><span style="color: #a0522d;">context</span>);
        <span style="color: #a020f0;">if</span> (is_array(<span style="color: #000000; background-color: #ffffff;">$</span><span style="color: #a0522d;">data</span>)) {
            <span style="color: #000000; background-color: #ffffff;">$</span><span style="color: #a0522d;">url</span> = <span style="color: #000000; background-color: #ffffff;">$</span><span style="color: #008b8b;">this</span>-&gt;<span style="color: #a0522d;">router</span>-&gt;<span style="color: #000000; background-color: #ffffff;">generate</span>(<span style="color: #8b2252;">'api_todos_get_item'</span>, [
                <span style="color: #8b2252;">'id'</span> =&gt; <span style="color: #000000; background-color: #ffffff;">$</span><span style="color: #a0522d;">object</span>-&gt;<span style="color: #000000; background-color: #ffffff;">getId</span>()
            ], <span style="color: #008b8b;">UrlGeneratorInterface</span>::<span style="color: #008b8b;">ABSOLUTE_URL</span>);
            <span style="color: #000000; background-color: #ffffff;">$</span><span style="color: #a0522d;">data</span>[<span style="color: #8b2252;">'url'</span>] = <span style="color: #000000; background-color: #ffffff;">$</span><span style="color: #a0522d;">url</span>;
        }

        <span style="color: #a020f0;">return</span> <span style="color: #000000; background-color: #ffffff;">$</span><span style="color: #a0522d;">data</span>;
    }

    <span style="color: #a020f0;">public</span> <span style="color: #a020f0;">function</span> <span style="color: #0000ff;">supportsDenormalization</span>(<span style="color: #000000; background-color: #ffffff;">$</span><span style="color: #a0522d;">data</span>, <span style="color: #000000; background-color: #ffffff;">$</span><span style="color: #a0522d;">type</span>, <span style="color: #000000; background-color: #ffffff;">$</span><span style="color: #a0522d;">format</span> = <span style="color: #008b8b;">null</span>)
    {
        <span style="color: #a020f0;">return</span> <span style="color: #000000; background-color: #ffffff;">$</span><span style="color: #008b8b;">this</span>-&gt;<span style="color: #a0522d;">decorated</span>-&gt;<span style="color: #000000; background-color: #ffffff;">supportsDenormalization</span>(<span style="color: #000000; background-color: #ffffff;">$</span><span style="color: #a0522d;">data</span>, <span style="color: #000000; background-color: #ffffff;">$</span><span style="color: #a0522d;">type</span>, <span style="color: #000000; background-color: #ffffff;">$</span><span style="color: #a0522d;">format</span>);
    }

    <span style="color: #a020f0;">public</span> <span style="color: #a020f0;">function</span> <span style="color: #0000ff;">denormalize</span>(<span style="color: #000000; background-color: #ffffff;">$</span><span style="color: #a0522d;">data</span>, <span style="color: #000000; background-color: #ffffff;">$</span><span style="color: #a0522d;">class</span>, <span style="color: #000000; background-color: #ffffff;">$</span><span style="color: #a0522d;">format</span> = <span style="color: #008b8b;">null</span>, <span style="color: #a020f0;">array</span> <span style="color: #000000; background-color: #ffffff;">$</span><span style="color: #a0522d;">context</span> = [])
    {
        <span style="color: #a020f0;">return</span> <span style="color: #000000; background-color: #ffffff;">$</span><span style="color: #008b8b;">this</span>-&gt;<span style="color: #a0522d;">decorated</span>-&gt;<span style="color: #000000; background-color: #ffffff;">denormalize</span>(<span style="color: #000000; background-color: #ffffff;">$</span><span style="color: #a0522d;">data</span>, <span style="color: #000000; background-color: #ffffff;">$</span><span style="color: #a0522d;">class</span>, <span style="color: #000000; background-color: #ffffff;">$</span><span style="color: #a0522d;">format</span>, <span style="color: #000000; background-color: #ffffff;">$</span><span style="color: #a0522d;">context</span>);
    }

    <span style="color: #a020f0;">public</span> <span style="color: #a020f0;">function</span> <span style="color: #0000ff;">setSerializer</span>(<span style="color: #228b22;">SerializerInterface</span> <span style="color: #000000; background-color: #ffffff;">$</span><span style="color: #a0522d;">serializer</span>)
    {
        <span style="color: #a020f0;">if</span>(<span style="color: #000000; background-color: #ffffff;">$</span><span style="color: #008b8b;">this</span>-&gt;<span style="color: #a0522d;">decorated</span> <span style="color: #a020f0;">instanceof</span> <span style="color: #228b22;">SerializerAwareInterface</span>) {
            <span style="color: #000000; background-color: #ffffff;">$</span><span style="color: #008b8b;">this</span>-&gt;<span style="color: #a0522d;">decorated</span>-&gt;<span style="color: #000000; background-color: #ffffff;">setSerializer</span>(<span style="color: #000000; background-color: #ffffff;">$</span><span style="color: #a0522d;">serializer</span>);
        }
    }
}
</pre>
</div>

935
<p>
Olivier Berger's avatar
Olivier Berger committed
936
937
938
939
The <code>normalize()</code> method accesses the router to generate the URL
corresponding to the GET on todo items (<code>api_todos_get_item</code>)
generated by api-platform (<code>bin/console debug:route</code>), storing it in
the <code>url</code> attribute.
940
941
942
</p>
</div>
</div>
Olivier Berger's avatar
Olivier Berger committed
943

Olivier Berger's avatar
Cleanup    
Olivier Berger committed
944
945
<div id="outline-container-org34d540a" class="outline-4">
<h4 id="org34d540a"><span class="section-number-4">4.4.6</span> Supporting PATCH request on Todo items</h4>
Olivier Berger's avatar
Olivier Berger committed
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
<div class="outline-text-4" id="text-4-4-6">
<p>
The PATCH method should be allowed on items, so we change the
<code>@ApiResource</code> to declare a <code>PATCH</code> <code>itemOperation</code>, as follows (we
must also explicitely declare GET and DELETE):
</p>

<div class="org-src-container">
<pre class="src src-php"><span style="color: #8b2252;">/**</span>
<span style="color: #8b2252;"> * ...</span>
<span style="color: #8b2252;"> * </span><span style="color: #008b8b;">@ApiResource</span><span style="color: #8b2252;">(</span>
<span style="color: #8b2252;"> *  ...</span>
<span style="color: #8b2252;"> *  itemOperations={</span>
<span style="color: #8b2252;"> *          "get",</span>
<span style="color: #8b2252;"> *          "patch"={</span>
<span style="color: #8b2252;"> *              "method"="PATCH"</span>
<span style="color: #8b2252;"> *              },</span>
<span style="color: #8b2252;"> *          "delete"</span>
<span style="color: #8b2252;"> *  })</span>
<span style="color: #8b2252;"> */</span>
<span style="color: #a020f0;">class</span> <span style="color: #228b22;">Todo</span>
{
</pre>
</div>
</div>
</div>

Olivier Berger's avatar
Cleanup    
Olivier Berger committed
973
974
<div id="outline-container-orgcdb1dc1" class="outline-4">
<h4 id="orgcdb1dc1"><span class="section-number-4">4.4.7</span> Fixing the order naming</h4>
Olivier Berger's avatar
Olivier Berger committed
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
<div class="outline-text-4" id="text-4-4-7">
<p>
Final step is to fix the naming of the <code>order</code> attribute, instead of <code>todo_order</code>.
</p>

<p>
Well just rename the <code>getTodoOrder()</code> and <code>setTodoOrder()</code> methods of
the <code>Todo</code> class to (resp.) <code>getOrder()</code> and <code>setOrder()</code>.
</p>

<p>
That's all about it. You should be able to run <a href="http://www.todobackend.com/client/index.html?http://127.0.0.1:8000/api/todos">http://www.todobackend.com/client/index.html?http://127.0.0.1:8000/api/todos</a> now
</p>
</div>
</div>
</div>
</div>

Olivier Berger's avatar
Cleanup    
Olivier Berger committed
993
994
<div id="outline-container-orgbd548b1" class="outline-2">
<h2 id="orgbd548b1"><span class="section-number-2">5</span> Deploying on heroku</h2>
Olivier Berger's avatar
Olivier Berger committed
995
996
997
998
<div class="outline-text-2" id="text-5">
<p>
Here are a few notes about the hardest part maybe that was the tuning necessary for hosting that API on heroku. Feel free to suggest complements.
</p>
Olivier Berger's avatar
Olivier Berger committed
999
</div>
Olivier Berger's avatar
Olivier Berger committed
1000

Olivier Berger's avatar
Cleanup    
Olivier Berger committed
1001
1002
<div id="outline-container-org7997f8f" class="outline-3">
<h3 id="org7997f8f"><span class="section-number-3">5.1</span> Support CORS</h3>
Olivier Berger's avatar
Olivier Berger committed
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
<div class="outline-text-3" id="text-5-1">
<p>
The test suite will now check that the CORS headers are supported. Test with :
<a href="http://www.todobackend.com/specs/index.html?http://127.0.0.1:8000/api/todos">http://www.todobackend.com/specs/index.html?http://127.0.0.1:8000/api/todos</a>
</p>

<p>
which should complain.
</p>

<p>
I added the <code>nelmio/cors-bundle</code> which is supposed to be well integrated with api-platform :
</p>
<div class="org-src-container">
<pre class="src src-sh">composer --no-ansi req cors
</pre>
1019
1020
</div>

Olivier Berger's avatar
Olivier Berger committed
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
<pre class="example">
Using version ^1.5 for nelmio/cors-bundle
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Nothing to install or update
Writing lock file
Generating autoload files
ocramius/package-versions:  Generating version class...
ocramius/package-versions: ...done generating version class
Executing script cache:clear [OK]
Executing script assets:install --symlink --relative public [OK]
</pre>
Olivier Berger's avatar
Olivier Berger committed
1034

1035
<p>
Olivier Berger's avatar
Cleanup    
Olivier Berger committed
1036
I then changed the <code>config/packages/nelmio_cors.yaml</code> in the following
Olivier Berger's avatar
Olivier Berger committed
1037
1038
way which is a variant of <a href="https://github.com/nelmio/NelmioCorsBundle">https://github.com/nelmio/NelmioCorsBundle</a>
since defaults didn't work well:
1039
1040
</p>
<div class="org-src-container">
Olivier Berger's avatar
Olivier Berger committed
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
<pre class="src src-yaml"><span style="color: #a0522d;">nelmio_cors</span>:
    <span style="color: #a0522d;">defaults</span>:
        <span style="color: #a0522d;">allow_credentials</span>: <span style="color: #008b8b;">false</span>
        <span style="color: #a0522d;">allow_origin</span>: []
        <span style="color: #a0522d;">allow_headers</span>: []
        <span style="color: #a0522d;">allow_methods</span>: []
        <span style="color: #a0522d;">expose_headers</span>: []
        <span style="color: #a0522d;">max_age</span>: 0
        <span style="color: #a0522d;">hosts</span>: []
        <span style="color: #b22222;">#</span><span style="color: #b22222;">&#160;Important since allow_origin contains '*'</span>
        <span style="color: #a0522d;">origin_regex</span>: <span style="color: #008b8b;">false</span>
    <span style="color: #a0522d;">paths</span>:
        <span style="color: #a0522d;">'^/'</span>:
            <span style="color: #a0522d;">allow_origin</span>: [<span style="color: #8b2252;">'*'</span>]
            <span style="color: #a0522d;">allow_headers</span>: [<span style="color: #8b2252;">'X-Custom-Auth'</span>, <span style="color: #8b2252;">'Origin'</span>, <span style="color: #8b2252;">'Content-Type'</span>, <span style="color: #8b2252;">'Accept'</span>]
            <span style="color: #a0522d;">allow_methods</span>: [<span style="color: #8b2252;">'POST'</span>, <span style="color: #8b2252;">'PUT'</span>, <span style="color: #8b2252;">'GET'</span>, <span style="color: #8b2252;">'DELETE'</span>, <span style="color: #8b2252;">'PATCH'</span>, <span style="color: #8b2252;">'OPTIONS'</span>]
            <span style="color: #a0522d;">max_age</span>: 3600
            <span style="color: #b22222;"># </span><span style="color: #b22222;">This may not be needed ?</span>
            <span style="color: #a0522d;">forced_allow_origin_value</span>: <span style="color: #8b2252;">'*'</span>
1060
1061
</pre>
</div>
Olivier Berger's avatar
Olivier Berger committed
1062
1063
1064
1065
1066
1067

<p>
This made the CORS headers work locally with
<a href="http://www.todobackend.com/specs/index.html?http://127.0.0.1:8000/api/todos">http://www.todobackend.com/specs/index.html?http://127.0.0.1:8000/api/todos</a>,
with the Symfony dev environment, using the <code>php -S</code> Web server.
</p>
1068
1069
1070
</div>
</div>

Olivier Berger's avatar
Cleanup    
Olivier Berger committed
1071
1072
<div id="outline-container-orgc7b167a" class="outline-3">
<h3 id="orgc7b167a"><span class="section-number-3">5.2</span> Tuning Heroku for REST API</h3>
Olivier Berger's avatar
Olivier Berger committed
1073
<div class="outline-text-3" id="text-5-2">
1074
1075
<p>
I had to tweak the Web server configuration (see <a href="Procfile">Procfile</a> and
Olivier Berger's avatar
Olivier Berger committed
1076
<a href="nginx_app.conf">nginx_app.conf</a> files) to make CORS work when deploying on heroku&#x2026; probably far from
1077
perfect. It worked locally, but I guess the heroku reverse proxy
Olivier Berger's avatar
Olivier Berger committed
1078
messes around&#x2026; or the PHP config&#x2026; or nginx&#x2026; anyway, it works now, with this custom config.
1079
1080
</p>

Olivier Berger's avatar
Olivier Berger committed
1081
1082
1083
<p>
Here's a quick reminder of what I changed for deployment:
</p>
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
<div class="org-src-container">
<pre class="src src-sh">heroku config:set <span style="color: #a0522d;">APP_ENV</span>=prod
<span style="color: #b22222;">#</span><span style="color: #b22222;">heroku config:set "CORS_ALLOW_ORIGIN=*"</span>
heroku config:set <span style="color: #8b2252;">"DATABASE_URL=sqlite:///%kernel.project_dir%/var/data.db"</span>
</pre>
</div>
</div>
</div>
</div>
</div>
<div id="postamble" class="status">
<p class="author">Author: Olivier Berger</p>
Olivier Berger's avatar
Cleanup    
Olivier Berger committed
1096
<p class="date">Created: 2018-05-14 lun. 16:05</p>
1097
1098
1099
1100
<p class="validation"><a href="http://validator.w3.org/check?uri=referer">Validate</a></p>
</div>
</body>
</html>