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 :: controlling the mouse with pynput 
Python :: torch.nan_to_num 
Python :: change xlabel python 
Python :: pandas mean of n columns 
Python :: python keyerror 
Python :: every second value python 
Python :: subscriptable meaning in python 
Python :: gfg placement course 
Python :: clipboard python 
Python :: pandas get higher value of column 
Python :: django insert bulk data 
Python :: how to make a new column with explode pyspark 
Python :: Count Zero 
Python :: Convert Int to String Using format() method 
Python :: Send Fetch Request Django(Get Method) 
Python :: access element from list python 
Python :: pandas assign multiple columns at once 
Python :: allow x_frame_options django 
Python :: filter field set in django formds 
Python :: use latest file on aws s3 bucket python 
Python :: Pass arguments in button tkinter 
Python :: how can you know if a year is a leap year 
Python :: fun games 
Python :: insert into string python 
Python :: guessing game python 
Python :: dockerize django 
Python :: variable globale python 
Python :: python list intersection 
Python :: gcd function in python 
Python :: pandas using eval converter excluding nans 
ADD CONTENT
Topic
Content
Source link
Name
7+1 =