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

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 :: four digit representation python 
Python :: no python application found, check your startup logs for errors 
Python :: download image from url 
Python :: list to csv python 
Python :: check if string equals string in list python 
Python :: closedxml hide column 
Python :: reading a file line by line using a generator 
Python :: py2exe no console 
Python :: pip install opencv 
Python :: re.sub in python example 
Python :: serialization in django 
Python :: python list to dict 
Python :: dynamic plot jupyter notebook 
Python :: anaconda 
Python :: convert pandas dataframe to numpy dataframe 
Python :: How to import HTML code into python with selenium webdriver 
Python :: python try else 
Python :: python counter nested dictionary 
Python :: create a python api 
Python :: distinct query in django queryset 
Python :: range of y & x in scatter 
Python :: creating a bar plot bar | creating a bar chart 
Python :: how to go up levels in path python 
Python :: plt tickpad 
Python :: regex find email address in string python 
Python :: how to use css in php example 
Python :: Python NumPy asfarray Function Example Scalar to float type array 
Python :: python pandas how to select range of data 
Python :: python socket get client ip 
Python :: pass arguments with apply 
ADD CONTENT
Topic
Content
Source link
Name
9+6 =