generated from nighthawkcoders/flask_portfolio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.py
97 lines (81 loc) · 2.79 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
from flask import Blueprint, jsonify # jsonify creates an endpoint response object
from flask_restful import Api, Resource # used for REST API building
import requests # used for testing
import random
from model_jokes import *
app_api = Blueprint('api', __name__,
url_prefix='/api/jokes')
# API generator https://flask-restful.readthedocs.io/en/latest/api.html#id1
api = Api(app_api)
class JokesAPI:
# not implemented
class _Create(Resource):
def post(self, joke):
pass
# getJokes()
class _Read(Resource):
def get(self):
return jsonify(getJokes())
# getJoke(id)
class _ReadID(Resource):
def get(self, id):
return jsonify(getJoke(id))
# getRandomJoke()
class _ReadRandom(Resource):
def get(self):
return jsonify(getRandomJoke())
# getRandomJoke()
class _ReadCount(Resource):
def get(self):
count = countJokes()
countMsg = {'count': count}
return jsonify(countMsg)
# put method: addJokeHaHa
class _UpdateLike(Resource):
def put(self, id):
addJokeHaHa(id)
return jsonify(getJoke(id))
# put method: addJokeBooHoo
class _UpdateJeer(Resource):
def put(self, id):
addJokeBooHoo(id)
return jsonify(getJoke(id))
# building RESTapi resources/interfaces, these routes are added to Web Server
api.add_resource(_Create, '/create/<string:joke>')
api.add_resource(_Read, '/')
api.add_resource(_ReadID, '/<int:id>')
api.add_resource(_ReadRandom, '/random')
api.add_resource(_ReadCount, '/count')
api.add_resource(_UpdateLike, '/like/<int:id>')
api.add_resource(_UpdateJeer, '/jeer/<int:id>')
if __name__ == "__main__":
# server = "http://127.0.0.1:5000" # run local
server = 'https://flask.nighthawkcodingsociety.com' # run from web
url = server + "/api/jokes"
responses = [] # responses list
# get count of jokes on server
count_response = requests.get(url+"/count")
count_json = count_response.json()
count = count_json['count']
# update likes/dislikes test sequence
num = str(random.randint(0, count-1)) # test a random record
responses.append(
requests.get(url+"/"+num) # read joke by id
)
responses.append(
requests.put(url+"/like/"+num) # add to like count
)
responses.append(
requests.put(url+"/jeer/"+num) # add to jeer count
)
# obtain a random joke
responses.append(
requests.get(url+"/random") # read a random joke
)
# cycle through responses
for response in responses:
print(response)
try:
print(response.json())
except:
print("unknown error")