This repository has been archived by the owner on Mar 8, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
api.py
360 lines (303 loc) · 10.1 KB
/
api.py
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
from flask import Blueprint, request, jsonify, abort
import json
from models import db_drop_and_create_all, setup_db, db, Actor, Movie
from auth import AuthError, requires_auth
casting_blueprint = Blueprint('gsprod-api', __name__)
# ROUTES
'''
GET /movies | GET /actors
it should be a authorized endpoint for avialable to all roles except 'public'
it should contain only the item's data representation
returns status code 200 and json {"success": True, "item": items} where items is the list of movies or actors
or appropriate status code indicating reason for failure
'''
@casting_blueprint.route('/movies', methods=['GET'])
@requires_auth('get:movies')
def get_movies(jwt):
"""Returns a list of objects with a short-form representation of movies or actors"""
all_movies = Movie.query.all()
if all_movies is None:
abort(404, 'There are no movies available')
formatted_movies = [movie.format() for movie in all_movies]
return jsonify({
'success': True,
'movies': formatted_movies
}), 200
@casting_blueprint.route('/actors', methods=['GET'])
@requires_auth('get:actors')
def get_actors(jwt):
"""Returns a list of objects with a short-form representation of actors"""
all_actors = Actor.query.all()
if all_actors is None:
abort(404, 'There are no actors available')
formatted_actor = [actor.format() for actor in all_actors]
return jsonify({
'success': True,
'actors': formatted_actor
}), 200
'''
GET /actors/<id> | GET /movies/<id>
where <id> is the existing model id
it should respond with a 404 error if <id> is not found
it should update the corresponding row for <id>
it should contain the item's data representation
returns status code 200 and json {"success": True, "item": item} where item is dictonary containing only the requested item
or appropriate status code indicating reason for failure
'''
@casting_blueprint.route('/movies/<int:movie_id>', methods=['GET'])
@requires_auth('get:movies')
def get_movie(jwt, movie_id):
print('getting movie for id: {}'.format(movie_id))
movie = Movie.query.filter(Movie.id == movie_id).one_or_none()
if movie:
return jsonify({
'success': True,
'movie': movie.format()
}), 200
else:
abort(404, 'Actor with id: {} not found'.format(movie_id))
@casting_blueprint.route('/actors/<int:actor_id>', methods=['GET'])
@requires_auth('get:actors')
def get_actor(jwt, actor_id):
actor = Actor.query.get(actor_id)
if actor:
return jsonify({
'success': True,
'actor': actor.format()
}), 200
else:
abort(404, 'Actor with id: {} not found'.format(actor_id))
'''
POST /movies | POST /actors
it should create a new row in the correct table
it should require the 'post:item' permission
returns status code 200 and json {"success": True, "items": item} where items is an array containing only the newly created item
or appropriate status code indicating reason for failure
'''
@casting_blueprint.route('/movies', methods=['POST'])
@requires_auth('post:movies')
def post_movie(jwt):
"""Create a new Movie with the POST method"""
if request.method != 'POST':
abort(405)
data = request.get_json()
movie = Movie(
title=data['title'],
year=data['year']
)
try:
movie.insert()
print('success')
return jsonify({
'success': True,
'movie': movie.format()
}), 200
except Exception:
db.session.rollback()
abort(422)
finally:
db.session.close()
@casting_blueprint.route('/actors', methods=['POST'])
@requires_auth('post:actors')
def post_actor(jwt):
"""Create a new Actor with the POST method"""
if request.method != 'POST':
abort(405)
data = request.get_json()
actor = Actor(
name=data['name'],
age=data['age'],
gender=data['gender']
)
try:
actor.insert()
return jsonify({
'success': True,
'actor': actor.format()
}), 200
except Exception:
db.session.rollback()
abort(422)
finally:
db.session.close()
'''
PATCH /movies/<id> | PATCH /actors/<id> |
where <id> is the existing model id
it should respond with a 404 error if <id> is not found
it should update the corresponding row for <id>
it should require the 'patch:items' permission
it should contain the item data representation
returns status code 200 and json {"success": True, "movie": item} where item an array containing only the updated item
or appropriate status code indicating reason for failure
'''
@casting_blueprint.route('/movies/<int:movie_id>', methods=['PATCH'])
@requires_auth('patch:movies')
def patch_movie(jwt, movie_id):
"""Update a pre-existing Movie using the PATCH method"""
data = request.get_json()
movie = Movie.query.get(movie_id)
if movie is None:
abort(404, 'Movie not found')
try:
movie.title = data.get('title')
movie.year = data.get('year')
movie.update()
return jsonify({
'success': True,
'movies': [movie.format()]
}), 200
except Exception:
db.session.rollback()
abort(422)
finally:
db.session.close()
@casting_blueprint.route('/actors/<int:actor_id>', methods=['PATCH'])
@requires_auth('patch:actors')
def patch_actor(jwt, actor_id):
"""Update a pre-existing Actor using the PATCH method"""
data = request.get_json()
actor = Actor.query.get(actor_id)
if actor is None:
abort(404, 'Actor not found')
try:
actor.title = data.get('title')
actor.name = data.get('name')
actor.age = data.get('age')
actor.gender = data.get('gender')
actor.update()
return jsonify({
'success': True,
'actors': [actor.format()]
}), 200
except Exception:
db.session.rollback()
abort(422)
finally:
db.session.close()
'''
DELETE /movies/<id> | DELETE /actors/<id>
where <id> is the existing model id
it should respond with a 404 error if <id> is not found
it should delete the corresponding row for <id>
it should require the 'delete:item' permission
returns status code 200 and json {"success": True, "delete": id} where id is the id of the deleted record
or appropriate status code indicating reason for failure
'''
@casting_blueprint.route('/movies/<int:movie_id>', methods=['DELETE'])
@requires_auth('delete:movies')
def delete_movie(jwt, movie_id):
"""Delete an existing movie using the DELETE method"""
movie = Movie.query.filter(Movie.id == movie_id).one_or_none()
if movie is None:
abort(404, 'Movie not found.')
try:
movie.delete()
return jsonify({
'success': True,
'delete': movie_id
}), 200
except Exception:
db.session.rollback()
abort(422)
finally:
db.session.close()
@casting_blueprint.route('/actors/<int:actor_id>', methods=['DELETE'])
@requires_auth('delete:actors')
def delete_actor(jwt, actor_id):
"""Delete an existing actor using the DELETE method"""
actor = Actor.query.filter(Actor.id == actor_id).one_or_none()
if actor is None:
abort(404, 'Actor not found.')
try:
actor.delete()
return jsonify({
'success': True,
'delete': actor_id
}), 200
except Exception:
db.session.rollback()
abort(422)
finally:
db.session.close()
# Error Handling
@casting_blueprint.errorhandler(422)
def unprocessable(error):
'''error handler for unprocessable entity'''
return jsonify({
"success": False,
"error": 422,
"message": "unprocessable"
}), 422
@casting_blueprint.errorhandler(400)
def bad_request(error):
'''error handler for bad request'''
return jsonify({
'success': False,
'error': 400,
'message': 'bad request'
}), 400
@casting_blueprint.errorhandler(405)
def method_not_allowed(error):
'''error handler for method not allowed'''
return jsonify({
'success': False,
'error': 405,
'message': 'method not allowed'
}), 405
@casting_blueprint.errorhandler(500)
def internal_sever_error(error):
'''error handler for internal server error'''
return jsonify({
'success': False,
'error': 500,
'message': 'internal server error'
}), 500
@casting_blueprint.errorhandler(404)
def not_found(error):
'''error handler for resource not found'''
return jsonify({
'success': False,
'error': 404,
'message': 'resource not found'
}), 404
@casting_blueprint.errorhandler(AuthError)
def permission_error(exception):
'''error handler for AuthError'''
return jsonify({
'error': exception.error['description'],
'status': exception.status_code
}), 401
@casting_blueprint.route('/seed')
def add_dummy_data():
'''Seed Database'''
db_drop_and_create_all()
actor1 = Actor(name="Sam Jones", age=25, gender='m')
actor2 = Actor(name="Cynthia Jones", age=22, gender='f')
actor3 = Actor(name="Vanna White", age=32, gender='f')
movie1 = Movie(title="The Movie", year=2015)
movie2 = Movie(title="The Movie 2", year=2016)
movie3 = Movie(title="The Movie 3", year=2017)
actor1.insert()
actor2.insert()
actor3.insert()
movie1.insert()
movie2.insert()
movie3.insert()
db.session.commit()
db.session.close()
return jsonify({
"success": 200,
"message": "db populated successfully"
})
@casting_blueprint.after_request
def after_request(response):
response.headers.add(
'Access-Control-Allow-Headers',
'Content-Type,Authorization,true'
)
response.headers.add(
'Access-Control-Allow-Methods',
'GET,PATCH,POST,DELETE,OPTIONS'
)
print('✅ response after_request', response)
return response