repl.it
@badvillain01/

rest api python

Python

creating rest api using python and flask

fork
loading
Files
  • main.py
  • Facts
  • Quotes
  • errormsg.json
  • Packager files
  • requirements.txt
main.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
from flask import Flask, jsonify
from threading import Thread
from flask_restful import Resource, Api
import json
import random

app = Flask('')
api = Api(app)

@app.route('/')
def home():
  return "I'm alive"



#################
##APi using Flask
###################
@app.route('/testing', methods=['GET'])
def testing():
  return jsonify({"Test" : "Successful"})  

@app.route('/api/add/<int:num>', methods=['GET'])
def add(num):
  return jsonify({f"{num} + {num}" : num + num})

@app.route('/api/name/<string:name>', methods=['GET'])
def get_name(name):
  return jsonify({"Your name": name})





#################################
##API USING FLASK-RESTFUL

class Test(Resource):
  def get(self):
    return jsonify({"Type": "flask-restful"})




def get_quotes(quote_type):
  if quote_type == "motivation":
    file_address = 'Quotes/motivation.json'
  elif quote_type == "funny":
    file_address = 'Quotes/funny.json'
  else:
    file_address = 'errormsg.json'  
  with open(file_address, 'r') as quotefile:
    data = json.load(quotefile)
  quote = random.choice(list(data['Quotes']))

  return quote


def get_facts(fact_type):
  if fact_type == "random":
    file_address = 'Facts/random.json'
  elif fact_type == "technology":
    file_address = 'Facts/technology.json'
  else:
    file_address = 'errormsg.json'  
  with open(file_address, 'r') as factfile:
    data = json.load(factfile)
  fact = random.choice(list(data['Facts']))

  return fact  


class Quotes(Resource):
  def get(self, quote_type):
    return get_quotes(quote_type)


class Facts(Resource):
  def get(self, fact_type):
    return get_facts(fact_type)

  

api.add_resource(Test, '/api/restful')
api.add_resource(Quotes, '/api/quotes/<string:quote_type>')
api.add_resource(Facts, '/api/facts/<string:fact_type>')

def run():
  app.run(host='0.0.0.0',port=7210)

  
t = Thread(target=run)
t.start()