Building a REST API in FLASK

Very simple question. I have a FLASK application which is postgresql behind it. There is no ORM for this application. All queries are executed through the psycopg2 SQL interface.

Now I want to set a specific API from this application. What will be the best way.

1> Also like: http://flask-peewee.readthedocs.org/en/latest/rest-api.html 2> or I can do it without ORM. It seems that the ORM for the RESTful API is very useful, but in this case I have to have separate database items and copy the data from the postgres model to the ORM.

Any suggestion would be welcome.

+8
source share
5 answers

I have a similar setup for Flask + Postgres and PsycoPG2. I have completed the following tutorials for developing and implementing an API. I handle errors manually and respond with the appropriate HTTP code.

http://blog.luisrei.com/articles/rest.html {API Design}

http://blog.luisrei.com/articles/flaskrest.html {implement API}

+7
source

Flask-Restless seems to be the best choice. Validation, authentication support is much easier with it.

+3
source

For non-trivial applications, it is better to use a flask class. Flask-Restless limits somewhat, and the soothing flask doesn’t really hold on to tights much, except that it is more complicated. I personally used a flask of anxiety for some time before moving on to tights.

+3
source

There are now several frameworks at the top of the bulb.

+2
source

REST API in FLASK app and Postman:

The code:

from flask_sqlalchemy import SQLAlchemy from flask import Flask,render_template,request,jsonify,json import psycopg2 import psycopg2.extras app = Flask(__name__) db = SQLAlchemy() conn = psycopg2.connect("postgresql://postgres: postgres@localhost :5432/country") cr = conn.cursor(cursor_factory=psycopg2.extras.DictCursor) @app.route('/', methods=['GET']) def test(): return jsonify({ 'message': 'Welcome' }) @app.errorhandler(404) def page_not_found(e): return "<h1>404</h1><p>The resource could not be found.</p>", 404 ##### Countries ###### @app.route('/country/all', methods=['GET']) def country(): cr.execute('select * from country') country = cr.fetchall() countries = [] for row in country: countries.append(dict(row)) return jsonify(countries) if __name__ == '__main__': app.run(debug=True, port=8080) 

Result:

enter image description here **

0
source

All Articles