Skip to content

Instantly share code, notes, and snippets.

@leon-sleepinglion
Last active November 5, 2022 00:59
Show Gist options
  • Save leon-sleepinglion/97bfd34132394e23ca5905ec730f776a to your computer and use it in GitHub Desktop.
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
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)
@shivamtomar77
Copy link

def post(self, name):
^
IndentationError: expected an indented block

How to solve it

@shivamtomar77
Copy link

/home/mtech/my_flask_app/venv/bin/python /home/mtech/my_flask_app/api.py
Traceback (most recent call last):
File "/home/mtech/my_flask_app/api.py", line 2, in
from flask_restful import Api, Resource, reqparse
File "/home/mtech/my_flask_app/flask_restful.py", line 2, in
from flask_restful import Resource, Api
ImportError: cannot import name 'Resource'

I installed packages but show this error
please solve it

@shivamtomar77
Copy link

It will Show
127.0.0.1 - - [05/Feb/2019 18:40:32] "GET / HTTP/1.1" 404 -
127.0.0.1 - - [05/Feb/2019 18:40:40] "GET /user/name HTTP/1.1" 405 -
127.0.0.1 - - [05/Feb/2019 18:40:50] "GET /user/name HTTP/1.1" 405 -

@Aishwarya4823
Copy link

Aishwarya4823 commented Feb 13, 2019

TypeError: get() missing 1 required positional argument: 'name' <- This is what shows upon running 127.0.0.1:5000/user/Aish . Please help.Why am I seeing this message ?

@mesrbn
Copy link

mesrbn commented Apr 17, 2019

@shivamtomar77 How did you solve the import issue?

@TepidDrink
Copy link

I POST a new user, GETting it fails, and PUTting it works somehow, not sure what is going on.

@LuisRocamonde
Copy link

@cloudydata
Copy link

These worked fine for me.....

GET
curl --request GET --url http://127.0.0.1:5000/user/Jass
this returns the JSON object for Jass

POST
curl --request POST --url http://127.0.0.1:5000/user/George
this adds another user named George

@JamesChan21
Copy link

Thanks for you help! I successfully use c socket to test it.
https://github.com/JamesChan21/Flask_And_C_Socket

@Algorithmism
Copy link

Algorithmism commented Oct 11, 2019

Why is it taking a GET request. Its nowhere specified in the code to take default GET function
How can we change it to another function(ex:POST)

http://127.0.0.1:5000/user/Marvin?age=29

^ That is the way you can do it in the URL.
You can also do it in the following way:
Change from "GET" to PUT.
Click on PARAMS
Under "Key" fill in the attribute of choice (age, occupation, etc.)
Under Value, fill in desired value (for example, 30).
POSTMAN

Then, click on SEND.

The following should be displayed in the body:
PostmanBody

@krstp
Copy link

krstp commented Nov 20, 2019

Why is it taking a GET request. Its nowhere specified in the code to take default GET function
How can we change it to another function(ex:POST)

Note you are calling User class in api.add_resource(User, "/api/user/<string:name>"). As you initialize HTTP call it will make a request for HTTP GET method. See console debug output:
127.0.0.1 - - [20/Nov/2019 17:31:41] "GET /api/user/Jass HTTP/1.1" 200 -

Three ways how to interact with data

Using CURL, you can add new user by using above posted:
curl --request POST --url http://127.0.0.1:5000/api/user/George

You can manipulate the data by using
curl -X PUT -H "Content-Type: application/json" -d '{"age":"23"}' http://127.0.0.1:5000/api/user/George

Notice: I am using different access path with /api/user/


Second way is by using Python's requests module, such as:
import requests
req = requests.get('http://127.0.0.1:5000/api/user/Nicholas')
req.text
req.json()

POST request:
requests.post('http://127.0.0.1:5000/api/user/Mike', data = {'age':57})


The third way is via user interface such as Insomia or Postman

I hope this helps. Good luck!

@maximencia
Copy link

Hi colleagues. How to run this with parameters from the command line host and port?

Thank u!

@leon-sleepinglion
Copy link
Author

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.

@dconnelly923
Copy link

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