Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

how to import flask restful using pip

pip install Flask-RESTful
Comment

creating an apis with python and flask

""" This website does pretty-good explanation with a working example
    
    https://programminghistorian.org/en/lessons/creating-apis-with-python-and-flask
"""
Comment

flask api


@app.route('/api/v1/users', methods=['GET'])
def get_users():
    users = [ user.json() for user in User.query.all() ] 
    return jsonify({'users': users })

@app.route('/api/v1/users/<id>', methods=['GET'])
def get_user(id):
    user = User.query.filter_by(id=id).first()
    if user is None:
        return jsonify({'message': 'User does not exists'}), 404

    return jsonify({'user': user.json() })
Comment

flask api

from flask import Flask
from flask_restful import Resource, Api

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

class HelloWorld(Resource):
    def get(self):
        return {'hello': 'world'}

api.add_resource(HelloWorld, '/')

if __name__ == '__main__':
    app.run(debug=True,port=8080)
Comment

python flask rest api

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

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

TODOS = {
    'todo1': {'task': 'build an API'},
    'todo2': {'task': '?????'},
    'todo3': {'task': 'profit!'},
}


def abort_if_todo_doesnt_exist(todo_id):
    if todo_id not in TODOS:
        abort(404, message="Todo {} doesn't exist".format(todo_id))

parser = reqparse.RequestParser()
parser.add_argument('task')


# Todo
# shows a single todo item and lets you delete a todo item
class Todo(Resource):
    def get(self, todo_id):
        abort_if_todo_doesnt_exist(todo_id)
        return TODOS[todo_id]

    def delete(self, todo_id):
        abort_if_todo_doesnt_exist(todo_id)
        del TODOS[todo_id]
        return '', 204

    def put(self, todo_id):
        args = parser.parse_args()
        task = {'task': args['task']}
        TODOS[todo_id] = task
        return task, 201


# TodoList
# shows a list of all todos, and lets you POST to add new tasks
class TodoList(Resource):
    def get(self):
        return TODOS

    def post(self):
        args = parser.parse_args()
        todo_id = int(max(TODOS.keys()).lstrip('todo')) + 1
        todo_id = 'todo%i' % todo_id
        TODOS[todo_id] = {'task': args['task']}
        return TODOS[todo_id], 201

##
## Actually setup the Api resource routing here
##
api.add_resource(TodoList, '/todos')
api.add_resource(Todo, '/todos/<todo_id>')


if __name__ == '__main__':
    app.run(debug=True)
Comment

basic flask api

# main.py
from flask import Flask, request
...
@app.route('/basic_api/entities', methods=['GET', 'POST'])
def entities():
    if request.method == "GET":
        return {
            'message': 'This endpoint should return a list of entities',
            'method': request.method
        }
    if request.method == "POST":
        return {
            'message': 'This endpoint should create an entity',
            'method': request.method,
		'body': request.json
        }

@app.route('/basic_api/entities/<int:entity_id>', methods=['GET', 'PUT', 'DELETE'])
def entity(entity_id):
    if request.method == "GET":
        return {
            'id': entity_id,
            'message': 'This endpoint should return the entity {} details'.format(entity_id),
            'method': request.method
        }
    if request.method == "PUT":
        return {
            'id': entity_id,
            'message': 'This endpoint should update the entity {}'.format(entity_id),
            'method': request.method,
		'body': request.json
        }
    if request.method == "DELETE":
        return {
            'id': entity_id,
            'message': 'This endpoint should delete the entity {}'.format(entity_id),
            'method': request.method
        }
Comment

PREVIOUS NEXT
Code Example
Python :: log in python 
Python :: telegram.ext package 
Python :: python loop with index 
Python :: Reading Custom Delimited 
Python :: change a color on touch roblox 
Python :: fast way to load mongodb data into python list 
Python :: Using Python-docx to update cell content of a table 
Python :: full row visible in jupyter notebook 
Python :: sklearn grid search cross validation show progress 
Python :: find an element using id in requests-html library in python 
Python :: cmake python interpreter 
Python :: define a string in python 
Python :: get all functions from a module as string list python 
Python :: import in python 
Python :: add colorbar without changing subplot size 
Python :: selenium proxy with authentication 
Python :: python try 
Python :: sample classification pipeline with hyperparameter tuning 
Python :: True Positive, True Negative, False Positive, False Negative in scikit learn 
Python :: python defualt error handler 
Python :: python print main arguments 
Python :: python cast number to between 0 and 1 
Python :: python init dict by list 
Python :: scipy.optimize.curve_fit 3D 
Python :: git clone in python to tmp directory 
Python :: python iterate over tuple of lists 
Python :: matplotlib force scientific notation and define exponent 
Python :: python make dict 
Python :: histogram relative frequency 
Python :: append string variable with integer python 
ADD CONTENT
Topic
Content
Source link
Name
2+2 =