forked from alessandrocucci/Restapi_Talk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
952 lines (846 loc) · 25.6 KB
/
index.html
File metadata and controls
952 lines (846 loc) · 25.6 KB
1
2
3
4
5
6
7
8
9
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
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
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
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
780
781
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
812
813
814
815
816
817
818
819
820
821
822
823
824
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
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>PyRE - Python Rest Api using Flask and SQLAlchemy</title>
<meta name="description" content="Building a Rest API using Flask and SQLAlchemy">
<meta name="author" content="Alessandro Cucci">
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, minimal-ui">
<link rel="stylesheet" href="css/reveal.css">
<link rel="stylesheet" href="css/theme/moon.css" id="theme">
<link rel="stylesheet" href="plugin/fullscreen/fullscreen.css">
<!-- Code syntax highlighting - also available: visualstudio.css & zenburn.css -->
<link rel="stylesheet" href="lib/css/darcula.css">
<!-- Icons -->
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
<!-- Printing and PDF exports -->
<script>
var link = document.createElement( 'link' );
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = window.location.search.match( /print-pdf/gi ) ? 'css/print/pdf.css' : 'css/print/paper.css';
document.getElementsByTagName( 'head' )[0].appendChild( link );
</script>
<!--[if lt IE 9]>
<script src="lib/js/html5shiv.js"></script>
<![endif]-->
</head>
<body>
<div class="reveal moon">
<!-- Any section element inside of this container is displayed as a slide -->
<div class="slides">
<section>
<div class="accent">
<h1>Rest API</h1>
<h2>using Flask & SQLAlchemy</h2>
</div>
<small>Alessandro Cucci<br />Python Developer, Energee3</small>
<aside class="notes">
Hi, I'm a Speaker Note. You can open the Speaker View by hitting [S] on your keyboard.
</aside>
</section>
<section>
<h2>Representational State Transfer</h2>
<h3>Roy Thomas Fielding - 2010</h3>
<h4><i>http://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm</i></h4>
</section>
<section>
<h1>REST <h2 class="alt">guiding constraints</h2></h1>
<div id="left">
<h3>
<ul>
<li class="fragment fade-in">Client-Server</li>
<li class="fragment fade-in">Stateless</li>
<li class="fragment fade-in">Cacheable</li>
<li class="fragment fade-in">Layered system</li>
<li class="fragment fade-in">Code on demand (optional)</li>
</ul>
</h3>
</div>
<div id='right'>
<h6>
<ul>
<li class="fragment fade-in">Uniform interface
<ul>
<li><h6>Identification of resources</h6></li>
<li><h6>Manipulation of resources through representations</h6></li>
<li><h6>Self-descriptive messages</h6></li>
<li><h6>Hypermedia as the engine of application state</h6></li>
</ul>
</li>
</ul>
</h6>
</div>
</section>
<section>
<h2 style="color: green">REST URI Examples</h2>
<ul>
<li>http://myapi.com/customers</li>
<li>http://myapi.com/customers/33245</li>
</ul>
<h1></h1>
<h2 style="color: red">REST Anti-Patterns</h2>
<ul>
<li>http://myapi.com/update_customer&id=12345&format=json</li>
<li>http://myapi.com/customers/12345/update</li>
</ul>
</section>
<section>
<h2>Relationship between URL and HTTP methods</h2>
<div style="font-size: 60%; width:100%">
<table>
<tr>
<th colspan="2">URL</th>
<th>GET</th>
<th>PUT</th>
<th>POST</th>
<th>DELETE</th>
</tr>
<tr>
<td colspan="2">http://api.myvinylcollection.com/records/</td>
<td>LIST of records in collection</td>
<td>Method not allowed.</td>
<td>CREATE a new entry in the collection.</td>
<td>DELETE the entire collection.</td>
</tr>
<tr>
<td colspan="2">http://api.myvinylcollection.com/records/1</td>
<td>RETRIEVE a representation of the addressed member of the collection</td>
<td>REPLACE the addressed member of the collection.</td>
<td>Method not allowed.</td>
<td>DELETE the addressed member of the collection.</td>
</tr>
</table>
</div>
</section>
<section>
<h2>What do we not care for this evening</h2>
<ul class="fragment fade-in">
<li>Stability & Testing</li>
<li>Long-Term maintainability</li>
<li>Edge Cases</li>
<li>Operations, Caching & Deployment</li>
</ul>
</section>
<section data-background-image="assets/vinyls.png">
<h1 style="color: red">My Vinyl Collection API</h1>
</section>
<section>
<img src="assets/flask.png" />
<h3>http://flask.pocoo.org/</h3>
</section>
<section>
<h2>Hello API!</h2>
<pre><code data-trim contenteditable>
from flask import Flask
app = Flask(__name__)
if __name__ == '__main__':
app.run()
</code></pre>
<pre class="fragment fade-in"><code data-trim contenteditable>
$ python myvinylcollectionapi.py
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
</code></pre>
<img class="fragment fade-in" src="assets/output/1.png" />
</section>
<section>
<h2>Hello API!</h2>
<pre><code data-trim contenteditable>
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello PyRE!"
if __name__ == '__main__':
app.run()
</code></pre>
<img class="fragment fade-in" src="assets/output/2.png" />
</section>
<section data-transition="convex">
<h2>Hello API!</h2>
<pre><code data-trim contenteditable>
from flask import Flask, jsonify
app = Flask(__name__)
@app.route("/")
def hello():
return jsonify(data="Hello PyRE!")
if __name__ == '__main__':
app.run()
</code></pre>
<img class="fragment fade-in" src="assets/output/3.png" />
</section>
<section>
<h1>HTTP GET Methods</h1>
<table class="fragment fade-in">
<tr>
<th colspan="2">URL</th>
<th>GET</th>
</tr>
<tr>
<td colspan="2">http://api.myvinylcollection.com/records</td>
<td>LIST of records in collection</td>
</tr>
<tr>
<td colspan="2">http://api.myvinylcollection.com/records/1</td>
<td>RETRIEVE a representation of the addressed member of the collection</td>
</tr>
</table>
</section>
<section>
<pre><code data-trim contenteditable>
from flask import Flask, jsonify, abort
app = Flask(__name__)
RECORDS = [
{
'id': 0,
'artist': "Queen",
'title': "A Night At The Opera",
'year': "1975",
'label': "EMI"
},
{
'id': 1,
'artist': "Pink Floyd",
'title': "The Dark Side Of The Moon",
'year': "1989",
'label': "EMI"
},
...
]
</code></pre>
</section>
<section>
<pre><code>
@app.route("/records")
def get_records():
return jsonify(RECORDS)
@app.route("/records/<int:index>")
def get_record(index):
try:
record = RECORDS[index]
except IndexError:
abort(404)
return jsonify(record)
if __name__ == '__main__':
app.run()
</code></pre>
</section>
<section>
<h2>HTTP GET Method</h2>
<pre><code data-trim contenteditable>
$ curl -X GET localhost:5000/records
[
{
"artist": "Queen",
"id": 0,
"label": "EMI",
"title": "A Night At The Opera",
"year": "1975"
},
{
"artist": "Pink Floyd",
"id": 1,
"label": "EMI",
"title": "The Dark Side Of The Moon",
"year": "1989"
}
]
</code></pre>
</section>
<section>
HTTP GET Method
<pre><code data-trim contenteditable>
$ curl -X GET localhost:5000/records/1
{
"artist": "Pink Floyd",
"id": 1,
"label": "EMI",
"title": "The Dark Side Of The Moon",
"year": "1989"
}
</code></pre>
<pre class="fragment fade-in"><code>
$ curl -X GET localhost:5000/records/5
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>404 Not Found</title>
<h1>Not Found</h1>
<p>The requested URL was not found on the server.
If you entered the URL manually please check
your spelling and try again.</p>
</code></pre>
</section>
<section>
<h2>Jsonify that error!</h2>
<pre><code data-trim contenteditable>
@app.errorhandler(404)
def page_not_found(error):
return jsonify(
error="Not Found",
status_code=404
), 404
</code></pre>
<pre class="fragment fade-in"><code data-trim contenteditable>
$ curl -X GET localhost:5000/records/5
{
"error": "Not Found",
"status_code": 404
}
</code></pre>
</section>
<section>
<div>
<h1>Good News:</h1>
<h2 style="color: green">It Works!</h2>
</div>
<div class="fragment fade-in">
<h1>Bad News:</h1>
<h2 style="color: red">Static Data</h2>
</div>
</section>
<section>
<h3>Separation of concerns</h3>
<img src="assets/separation.png" />
</section>
<section>
<h2>
<span>Sqlite </span>
<span class="fragment fade-in">+ Discogs.com </span>
<span class="fragment fade-in">+ Pandas</span>
</h2>
</section>
<section>
<pre><code>
CREATE TABLE "collection" (
`index` INTEGER PRIMARY KEY AUTOINCREMENT,
`Catalog#` TEXT,
`Artist` TEXT,
`Title` TEXT,
`Label` TEXT,
`Format` TEXT,
`Rating` REAL,
`Released` INTEGER,
`release_id` INTEGER,
`CollectionFolder` TEXT,
`Date Added` TEXT,
`Collection Media Condition` TEXT,
`Collection Sleeve Condition` TEXT,
`Collection Notes` REAL
)
</code></pre>
</section>
<section>
<h2>CSV Collection Export</h2>
<img src="assets/discogs.png" />
</section>
<section>
<pre><code data-trim contenteditable>
import pandas
import sqlite3
conn = sqlite3.connect('record_collection.db')
conn.text_factory = sqlite3.Binary
df = pandas.read_csv('collection.csv')
df.to_sql('collection', conn)
</code></pre>
</section>
<section>
<img src="assets/sqlite.png" />
</section>
<section>
<h2>Object Relational Mapper (ORM)</h2>
<img class="fragment fade-in" src="assets/sqlalchemy.png" />
<h3 class="fragment fade-in">http://docs.sqlalchemy.org</h3>
</section>
<section>
<h2>model.py</h2>
<pre><code>
from flask_sqlalchemy import SQLAlchemy
from flask_sqlalchemy import orm
db = SQLAlchemy()
class Record(db.Model):
__tablename__ = "collection"
index = db.Column(db.Integer, primary_key=True)
Artist = db.Column(db.Text, nullable=False)
Title = db.Column(db.Text, nullable=False)
Label = db.Column(db.Text)
Released = db.Column(db.Text)
def as_dict(self):
columns = orm.class_mapper(self.__class__).mapped_table.c
return {
col.name: getattr(self, col.name)
for col in columns
}
</code></pre>
</section>
<section>
<h3>Query</h3>
<pre class="fragment fade-in"><code>
>>> # .all() return a list
>>> all_records = Record.query.all()
>>> len(all_records)
80
</code></pre>
<pre class="fragment fade-in"><code>
>>> # .first() return the first item that matches
>>> record = Record.query.filter(Record.index == 9).first()
>>> record.Title
"Back In Black"
>>> record.Artist
"AC/DC"
>>> record.Released
"1980"
</code></pre>
<pre class="fragment fade-in"><code>
>>> # .filter_by() is a shortcut
>>> record = Record.query.filter_by(index == 6).first()
>>> record.Title
"Hotel California"
</code></pre>
</section>
<section>
<pre><code>
from flask import Flask, jsonify
from model import db, Record
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///record_collection.db"
db.init_app(app)
@app.route("/records")
def get_records():
records = [r.as_dict() for r in Record.query.all()]
return jsonify(records)
@app.route("/records/<int:index>")
def get_record(index):
record = Record.query.filter(Record.index == index).first_or_404()
return jsonify(record.as_dict())
</code></pre>
</section>
<section>
<pre><code>
$ curl -X GET localhost:5000/records
[
{
"Artist": "The Police",
"index": 0,
"Title": "Reggatta De Blanc"
},
{
"Artist": "The Beatles",
"index": 1,
"Title": "Abbey Road"
},
...
]
</code></pre>
<pre><code>
$ curl -X GET localhost:5000/records/1
{
"Artist": "The Beatles",
"index": 1,
"Title": "Abbey Road"
}
</code></pre>
</section>
<section>
<h1>HTTP POST Methods</h1>
<table class="fragment fade-in">
<tr>
<th colspan="2">URL</th>
<th>POST</th>
</tr>
<tr>
<td colspan="2">http://api.myvinylcollection.com/records/</td>
<td>CREATE a new entry in the collection.</td>
</tr>
<tr>
<td colspan="2">http://api.myvinylcollection.com/records/1</td>
<td>Method not allowed.</td>
</tr>
</table>
</section>
<section>
<h3>Post on localhost:5000/records/id</h3>
<pre><code>
@app.errorhandler(405)
def method_not_allowed(error):
return jsonify(
error="Method Not Allowed",
status_code=405
), 405
</code></pre>
<pre class="fragment fade-in"><code>
from flask import Flask, jsonify, abort, request
...
@app.route("/records/<int:index>", methods=['GET', 'POST'])
def get_record(index):
if request.method == 'POST':
abort(405)
record = Record.query.filter(Record.index == index).first_or_404()
return jsonify(record.as_dict())
</code></pre>
</section>
<section>
<pre><code>
$ curl -X POST localhost:5000/records/1
{
"error": "Method Not Allowed",
"status_code": 405
}
</code></pre>
</section>
<section>
<h3>Insert into database</h3>
<pre class="fragment fade-in"><code>
>>> # .add() insert a record
>>> db.session.add(record)
</code></pre>
<pre class="fragment fade-in"><code>
>>> # changes won't be saved until committed!
>>> db.session.commit()
</code></pre>
</section>
<section>
<h2>Adding a record to my collection</h2>
<pre><code>
@app.route("/records", methods=['GET', 'POST'])
def get_records():
if request.method == 'POST':
record = Record(**json.loads(request.data))
db.session.add(record)
db.session.commit()
return jsonify(record.as_dict()), 201
records = [r.as_dict() for r in Record.query.all()]
return jsonify(records)
</code></pre>
</section>
<section>
<h2>Adding a record to my collection</h2>
<pre><code>
$ curl -i -H "Content-Type: application/json" -X POST localhost:5000/records \
> -d '{"Artist":"Neil Joung", "Title":"Harvest", \
> "Label":"Reprise Records", "Released":"1977"}'
HTTP/1.0 201 CREATED
Content-Type: application/json
Content-Length: 104
Server: Werkzeug/0.11.11 Python/2.7.12+
Date: Sat, 03 Dec 2016 11:03:10 GMT
{
"Artist": "Neil Young",
"Label": "Reprise Records",
"Released": "1977",
"Title": "American Stars 'N Bars",
"index": 91
}
</code></pre>
</section>
<section>
<h1>HTTP PUT methods</h1>
<table class="fragment fade-in">
<tr>
<th colspan="2">URL</th>
<th>PUT</th>
</tr>
<tr>
<td colspan="2">http://api.myvinylcollection.com/records/</td>
<td>Method not allowed.</td>
</tr>
<tr>
<td colspan="2">http://api.myvinylcollection.com/records/1</td>
<td>REPLACE the addressed member of the collection.</td>
</tr>
</table>
</section>
<section>
<pre><code>
@app.route("/records", methods=['GET', 'POST', 'PUT'])
def get_records():
if request.method == 'POST':
record = Record(**json.loads(request.data))
db.session.add(record)
db.session.commit()
return jsonify(record.as_dict()), 201
elif request.method == 'PUT':
abort(405)
records = [r.as_dict() for r in Record.query.all()]
return jsonify(records), 200
@app.route("/records/<int:index>", methods=['GET', 'POST', 'PUT'])
def get_record(index):
if request.method == 'POST':
abort(405)
else:
record = Record.query.filter(Record.index == index).first_or_404()
if request.method == 'PUT':
for k, v in json.loads(request.data).iteritems():
setattr(record, k, v)
db.session.add(record)
db.session.commit()
return jsonify(record.as_dict()), 200
</code></pre>
</section>
<section>
<h2>PUT on Collection</h2>
<pre><code>
$ curl -i -H "Content-Type: application/json" \
> -X POST localhost:5000/records \
> -d '{"Artist":"Neil Joung", "Title":"Harvest", \
> "Label":"Reprise Records", "Released":"1977"}'
HTTP/1.0 405 METHOD NOT ALLOWED
Content-Type: application/json
Content-Length: 59
Server: Werkzeug/0.11.11 Python/2.7.12+
Date: Sat, 03 Dec 2016 10:20:06 GMT
{
"error": "Method Not Allowed",
"status_code": 405
}
</code></pre>
</section>
<section>
<h2>PUT on Resource</h2>
<pre><code>
$ curl -i -H "Content-Type: application/json" \
> -X PUT localhost:5000/records/91 \
> -d '{"Artist":"Neil Joung", "Title":"Harvest", \
> "Label":"Reprise Records", "Released":"1977"}'
HTTP/1.0 200 OK
Content-Type: application/json
Content-Length: 104
Server: Werkzeug/0.11.11 Python/2.7.12+
Date: Sat, 03 Dec 2016 11:07:22 GMT
{
"Artist": "Neil Young",
"Label": "Reprise Records",
"Released": "1977",
"Title": "American Stars 'N Bars",
"index": 91
}
</code></pre>
</section>
<section>
<h1>HTTP DELETE methods</h1>
<table class="fragment fade-in">
<tr>
<th colspan="2">URL</th>
<th>DELETE</th>
</tr>
<tr>
<td colspan="2">http://api.myvinylcollection.com/records/</td>
<td>DELETE the entire collection.</td>
</tr>
<tr>
<td colspan="2">http://api.myvinylcollection.com/records/1</td>
<td>DELETE the addressed member of the collection.</td>
</tr>
</table>
</section>
<section>
<h2>DELETE on Collection</h2>
<pre><code>
@app.route("/records", methods=['GET', 'POST', 'PUT', 'DELETE'])
def get_records():
if request.method == 'POST':
record = Record(**json.loads(request.data))
db.session.add(record)
db.session.commit()
return jsonify(record.as_dict()), 201
elif request.method == 'PUT':
abort(405)
records = [r.as_dict() for r in Record.query.all()]
if request.method == 'DELETE':
for r in records:
db.session.delete(r)
db.session.commit()
records = [r.as_dict() for r in Record.query.all()]
return jsonify(records), 200
</code></pre>
</section>
<section>
<h2>DELETE on Resource</h2>
<pre><code>
@app.route("/records/<int:index>", methods=['GET', 'POST', 'PUT', 'DELETE'])
def get_record(index):
if request.method == 'POST':
abort(405)
else:
record = Record.query.filter(Record.index == index).first_or_404()
if request.method == 'PUT':
for k, v in json.loads(request.data).iteritems():
setattr(record, k, v)
db.session.add(record)
db.session.commit()
elif request.method == 'DELETE':
db.session.delete(record)
db.session.commit()
return jsonify(record.as_dict()), 200
</code></pre>
</section>
<section>
<h2>DELETE on Resource</h2>
<pre><code>
$ curl -i -X DELETE localhost:5000/records/91
HTTP/1.0 200 OK
Content-Type: application/json
Content-Length: 104
Server: Werkzeug/0.11.11 Python/2.7.12+
Date: Sat, 03 Dec 2016 10:40:00 GMT
{
"Artist": "Neil Young",
"Label": "Reprise Records",
"Released": "1977",
"Title": "American Stars 'N Bars",
"index": 91
}
</code></pre>
</section>
<section>
<h2>DELETE on Resource</h2>
<pre><code>
$ curl -i -X DELETE localhost:5000/records/91
HTTP/1.0 HTTP/1.0 404 NOT FOUND
Content-Type: application/json
Content-Length: 50
Server: Werkzeug/0.11.11 Python/2.7.12+
Date: Sat, 03 Dec 2016 10:40:09 GMT
{
"error": "Not Found",
"status_code": 404
}
</code></pre>
</section>
<section>
<h2>DELETE on Collection</h2>
<pre><code>
$ curl -i -X DELETE localhost:5000/records
</code></pre>
</section>
<section data-background-image="assets/atomic.jpg">
</section>
<section data-src="assets/gandalf.jpg">
<h1>Flask-Login</h1>
<h4>https://flask-login.readthedocs.io</h4>
<img src="assets/gandalf.jpg" style="width: 70%"/>
</section>
<section>
<h2>Pwd authentication</h2>
<pre><code>
from flask import Flask, jsonify, abort
from flask_login import LoginManager, current_user
app = Flask(__name__)
login_manager = LoginManager(app)
@login_manager.request_loader
def check_token(request):
token = request.headers.get('Authorization')
if token == 'L3T_M3_PA55!':
return "You_can_pass" # DON'T TRY THIS AT HOME!
return None
@app.route("/")
def get_main_root():
if current_user:
return jsonify(data='Hello Login'), 200
else:
abort(401)
</code></pre>
</section>
<section>
<h2>How it works</h2>
<pre><code>
$ curl -i localhost:5000
HTTP/1.0 401 UNAUTHORIZED
Content-Type: application/json
WWW-Authenticate: Basic realm="Authentication Required"
Content-Length: 37
Server: Werkzeug/0.11.11 Python/2.7.12+
Date: Sat, 03 Dec 2016 14:46:55 GMT
{
"error": "Unauthorized access"
}
</code></pre>
<pre class="fragment fade-in"><code>
$ curl -i -H "Authorization: L3T_M3_PA55!" localhost:5000
HTTP/1.0 200 OK
Content-Type: application/json
Content-Length: 28
Server: Werkzeug/0.11.11 Python/2.7.12+
Date: Sat, 03 Dec 2016 14:42:00 GMT
{
"data": "Hello Login"
}
</code></pre>
</section>
<section>
<h2>Securing our API - Resource</h2>
<pre><code>
@app.route("/records/<int:index>", methods=['GET', 'POST', 'PUT', 'DELETE'])
def get_record(index):
if request.method == 'POST':
abort(405)
else:
record = Record.query.filter(Record.index == index).first_or_404()
if request.method == 'PUT':
if current_user:
for k, v in json.loads(request.data).iteritems():
setattr(record, k, v)
db.session.add(record)
db.session.commit()
else:
abort(401)
elif request.method == 'DELETE':
if current_user:
db.session.delete(record)
db.session.commit()
else:
abort(401)
return jsonify(record.as_dict()), 200
</code></pre>
</section>
<section>
<h2>Securing our API - Collection</h2>
<pre><code>
@app.route("/records", methods=['GET', 'POST', 'PUT', 'DELETE'])
def get_records():
if request.method == 'POST':
record = Record(**json.loads(request.data))
db.session.add(record)
db.session.commit()
return jsonify(record.as_dict()), 201
elif request.method == 'PUT':
abort(405)
records = [r.as_dict() for r in Record.query.all()]
if request.method == 'DELETE':
if current_user:
for r in records:
db.session.delete(r)
db.session.commit()
records = [r.as_dict() for r in Record.query.all()]
return jsonify(records), 200
else:
abort(401)
return jsonify(records), 200
</code></pre>
</section>
<section>
<h2>Homeworks</h2>
<ul>
<li>Pagination with Flask-SqlAlchemy</li>
<li>Rate Limiting with Flask-Limiter</li>
<li>Cache with Flask-Cache</li>
</ul>
</section>
<section>
<h1>THANK YOU!</h1>
<br />
<pre><code>
{
'slides': 'www.alessandrocucci.it/pyre/restapi',
'code': 'https://goo.gl/4UOqEr'
}
</code></pre>
</section>
</div>
</div>
<script src="lib/js/head.min.js"></script>
<script src="js/reveal.js"></script>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script src="js/restapi.js"></script>
</body>
</html>