Ahmed Mohamed
Ahmed Mohamed

Reputation: 231

how to use python flask RESTful api with any python framework

I am a beginner in python web frameworks and i have created a simple Python-Flask RESTful API which enables me to get infromation from a database using GET request but i have a problem in how can i use this API with any website python based frameworks because i know each framework has it's own way to conenct Urls with the code so it will not be just add the .py file to the website files and invoke it from the Url like php, so how can i use this flask APi in any website with python framework like (Django, Flask, ..etc)? Thanks.

This is my simple API:

from flask import Flask, request
from flask_restful import Resource, Api
from sqlalchemy import create_engine
from json import dumps
from flask_jsonpify import jsonify
import MySQLdb
app = Flask(__name__)
api = Api(app)
db = MySQLdb.connect("localhost", "root", "root", "x")

class macros(Resource):
    def get(self):
        cursor = db.cursor()        
        cursor.execute("select * from survey_macro")  # This line will be changes from website to another      
        return jsonify({'macros':[i for i in cursor.fetchall()]})  

api.add_resource(macros, '/macros')  # Route_1

if __name__ == '__main__':
    app.run(port='5002')

Upvotes: 0

Views: 838

Answers (1)

kemis
kemis

Reputation: 4604

If you have a flask website you can just add that code to an existing file and it will work but it is better to use blueprints. Blueprints allow you to separate your code into smaller independent applications so for example you have one blueprint for one part of your website and another for your API.

If you have a django website you can write your API in django-restful. It is better to use just one framework then to have one part of the application written in one framework and another in a second.

One more option is to make your API a separate website and just send requests to it from any other website.

Upvotes: 1

Related Questions