Created
August 17, 2016 03:57
-
-
Save ethan-funny/cf19aa89175055de6517d851759ad743 to your computer and use it in GitHub Desktop.
flask restful api
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
from flask import Flask, jsonify, abort, make_response | |
from flask import request | |
app = Flask(__name__) | |
articles = [ | |
{ | |
'id': 1, | |
'title': 'the way to python', | |
'content': 'tuple, list, dict' | |
}, | |
{ | |
'id': 2, | |
'title': 'the way to REST', | |
'content': 'GET, POST, PUT' | |
} | |
] | |
@app.route('/blog/api/articles', methods=['GET']) | |
def get_articles(): | |
return jsonify({'articles': articles}) | |
@app.route('/blog/api/articles/<int:article_id>', methods=['GET']) | |
def get_article(article_id): | |
article = filter(lambda a: a['id'] == article_id, articles) | |
if len(article) == 0: | |
abort(404) | |
return jsonify({'article': article[0]}) | |
@app.route('/blog/api/articles', methods=['POST']) | |
def create_article(): | |
if not request.json or not 'title' in request.json: | |
abort(400) | |
article = { | |
'id': articles[-1]['id'] + 1, | |
'title': request.json['title'], | |
'content': request.json.get('content', '') | |
} | |
articles.append(article) | |
return jsonify({'article': article}), 201 | |
@app.route('/blog/api/articles/<int:article_id>', methods=['PUT']) | |
def update_article(article_id): | |
article = filter(lambda a: a['id'] == article_id, articles) | |
print article | |
if len(article) == 0: | |
abort(404) | |
if not request.json: | |
abort(400) | |
article[0]['title'] = request.json.get('title', article[0]['title']) | |
article[0]['content'] = request.json.get('content', article[0]['content']) | |
return jsonify({'article': article[0]}) | |
@app.route('/blog/api/articles/<int:article_id>', methods=['DELETE']) | |
def delete_article(article_id): | |
article = filter(lambda t: t['id'] == article_id, articles) | |
if len(article) == 0: | |
abort(404) | |
articles.remove(article[0]) | |
return jsonify({'result': True}) | |
@app.errorhandler(404) | |
def not_found(error): | |
return make_response(jsonify({'error': 'Not found'}), 404) | |
if __name__ == '__main__': | |
app.run(host='127.0.0.1', port=5632, debug=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment