Last active
November 5, 2022 00:59
-
-
Save leon-sleepinglion/97bfd34132394e23ca5905ec730f776a to your computer and use it in GitHub Desktop.
Python Flask REST API Tutorial on Medium. π https://codeburst.io/this-is-how-easy-it-is-to-create-a-rest-api-8a25122ab1f3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Hi colleagues. How to run this with parameters from the command line host and port?
Thank u!
Hi mate, you may use a Python built-in library called argparse to specify command line arguments.
Is there anyway to show a list of users that already exist?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi colleagues. How to run this with parameters from the command line host and port?
Thank u!