Which Flask extension should I choose to work with API's?

143 Views Asked by At

I've tried to work with Flask-Restless, but I'm not sure, I think its unable to work with factory pattern and blueprints.

I want to find something similar to Restless(simple generation/JSON format) but compatible with the factory pattern & blueprints so, Which FP&BP supported extension you recommend me to build an API under those requirements?

1

There are 1 best solutions below

1
Ian Ash On

You can build a REST API using Blueprints quite simply without relying on any Flask extensions.

This is a non-working example, but should help you get started. Set up a basic blueprint file (let's assume it's called user.py):

import json
from flask import Blueprint, jsonify, request
   
bp = Blueprint('user', __name__, url_prefix='/user')

@bp.route('/', methods=['GET', 'POST'])
def user_details():
    if request.method=='GET':
         # Access elements in the JSON passed in to the call using request.json
         # Return a JSON result by passing a dictionary to jsonify
         return jsonify({'result': 'ok', 'var1': 'val1'})

    if request.method == 'POST':
         # Access elements in the JSON passed in to the call using request.json
         # Return a JSON result by passing a dictionary to jsonify
        return jsonify({'result': 'ok')

and then just add the blue print to your Flask server as normal, e.g. your __init__.py will have something like this:

from flask import Flask
import user
app = Flask(__name__)
app.register_blueprint(user.bp)