Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

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 :: binary python 
Python :: dataframe pandas empty 
Python :: rust vs python 
Python :: python discord mention user 
Python :: return max value in list python 
Python :: python how to draw a circle 
Python :: how to click a div element in selenium python 
Python :: groupby where only 
Python :: puppy and sum codechef solution 
Python :: Python program to count Even and Odd numbers using lambda 
Python :: replace characters in string python 
Python :: how to print last element in a list python 
Python :: how to add subtitle to plot in python 
Python :: seaborn angle lable 
Python :: range of y & x in scatter 
Python :: pandas astype str still object 
Python :: code coverage pytest as html 
Python :: Replace all the empty rows in the column with the value that you have identified 
Python :: dataframe check for nan in iterrows 
Python :: list to dataframe columns 
Python :: how to load user from jwt token request django 
Python :: random normal 
Python :: print example in python 
Python :: raw input py 
Python :: list_display django foreign key 
Python :: find all unique substring permutations of a string of a specific length python 
Python :: indexing python first and last 
Python :: sum of multiples of 3 or 5 python 
Python :: try except 
Python :: jupyterlab interactive plot 
ADD CONTENT
Topic
Content
Source link
Name
1+1 =