Skip to content

Instantly share code, notes, and snippets.

@hadpro24
Forked from leon-sleepinglion/app.py
Created March 28, 2019 15:50
Show Gist options
  • Save hadpro24/286cc5fe27ebf92e56448802ed8de2d7 to your computer and use it in GitHub Desktop.
Save hadpro24/286cc5fe27ebf92e56448802ed8de2d7 to your computer and use it in GitHub Desktop.
from flask import Flask
from flask_restful import Api, Resource, reqparse
app = Flask(__name__)
api = Api(app)
users = [
{
"name": "Nicholas",
"age": 42,
"occupation": "Network Engineer"
},
{
"name": "Elvin",
"age": 32,
"occupation": "Doctor"
},
{
"name": "Jass",
"age": 22,
"occupation": "Web Developer"
}
]
class User(Resource):
def get(self, name):
for user in users:
if(name == user["name"]):
return user, 200
return "User not found", 404
def post(self, name):
parser = reqparse.RequestParser()
parser.add_argument("age")
parser.add_argument("occupation")
args = parser.parse_args()
for user in users:
if(name == user["name"]):
return "User with name {} already exists".format(name), 400
user = {
"name": name,
"age": args["age"],
"occupation": args["occupation"]
}
users.append(user)
return user, 201
def put(self, name):
parser = reqparse.RequestParser()
parser.add_argument("age")
parser.add_argument("occupation")
args = parser.parse_args()
for user in users:
if(name == user["name"]):
user["age"] = args["age"]
user["occupation"] = args["occupation"]
return user, 200
user = {
"name": name,
"age": args["age"],
"occupation": args["occupation"]
}
users.append(user)
return user, 201
def delete(self, name):
global users
users = [user for user in users if user["name"] != name]
return "{} is deleted.".format(name), 200
api.add_resource(User, "/user/<string:name>")
app.run(debug=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment