HomeProjectsArticlesNotesAbout

Flask REST API Notes

flask
notes

Requirement.txt

Flask-RESTful
Flask

Imports

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

Simple Route

#...
class HelloWorld(Resource):
  def get(self):
    return {"data": "hello world"}

  def post(self):
    return {"data": "posted"}

api.add_resource(HelloWorld, "/helloworld")

Test

import requests
BASE_URL = "http://127.0.0.1:5002/"
test_get = requests.get(BASE_URL + 'helloworld')
test_post = requests.post(BASE_URL + 'helloworld')
print(test_get.json())
print(test_post.json())

Param in URL

#...
class User(Resource):
  def get(self, user):
    return {"user": user}

api.add_resource(User, "/user/<string:user>")

Test

#....
# PARAM IN URL
test_user_get = requests.get(BASE_URL + 'user/steve')
print(test_user_get.json())

Argument Validation

Example - Simple

from flask_restful import reqparse
#....

parser = reqparser.RequestParser()
parser.add_argument('email', type=str, help="email is required", required=True)
#....

Example - Validate User Login Args

from flask_restful import reqparse
#....
user_login_args = reqparse.RequestParser()
user_login_args.add_argument("email", type=str, help="email is required", required=True)
user_login_args.add_argument("password", type=str, help="password", required=True)

class UserLogin(Resource):
  def put(self):
    args = user_login_args.parse_args()
    return {"data": args}

api.add_resource(UserLogin, "/user/login")
#....

Data Formatting

from flask_restful import fields, marshal_with

More Articles

All Articles

Links

Home Articles Notes Projects About Style Guide Site Credits

Contact

ย connect@dev.lucaszapico.space

Location

๐ŸŒŽ Earth