External Exam Download Resources Web Applications Games Recycle Bin

Developing a RESTful API

To install RESTful for Flask:

pip3 install flask_restful



RESTful1.py

from flask import Flask
from flask_restful import Api, Resource

app = Flask(__name__)
api = Api(app)

COUNTER = 3
CITIES = {
    1: 'Brisbane',
    2: 'Sydney'
}

class city(Resource):    
    def get(self):    
        return CITIES
         
class addcity(Resource):    
    def get(self, city):    
        global COUNTER
        global CITIES
        CITIES[COUNTER] = city
        COUNTER = COUNTER + 1
        return CITIES

api.add_resource(city, '/city/')
api.add_resource(addcity, '/addcity//')
app.run()

#-------------------------------------------
#try:
#http://127.0.0.1:5000/city/
#http://127.0.0.1:5000/addcity/London/

RESTful2.py

from flask import Flask
from flask_restful import reqparse, Api, Resource

app = Flask(__name__)
api = Api(app)

USERPASSWORDS = {
    "john":"abcd",
    "mary":"1234"
}

class users(Resource):
    def get(self): 
        parser = reqparse.RequestParser()
        parser.add_argument('username',default=None)
        parser.add_argument('password',default=None)
        args = parser.parse_args()
        if args['username'] is not None and args['password'] is not None:
            USERPASSWORDS[args['username']] = args['password']
        return USERPASSWORDS

api.add_resource(users, '/users/')
app.run()

#-------------------------------------------
#try:
#http://127.0.0.1:5000/users/
#http://127.0.0.1:5000/users/?username=test&password=yolo