1

I'm trying to build an api using Flask-restplus and Flask-Flask-Injector.

I searched and couldn't find an example on these two together.

All examples are on Flask, not the restplus one.

I tried to build using the following: ``

from flask import Flask
from flask_restplus import Api, Resource
from flask_injector import FlaskInjector, Injector, inject, singleton  

app = Flask(__name__)
app.secret_key = "123"
api = Api(app=app)  

class MyConf():
    def __init__(self, val: int):
        self.val = val

class MyApi(Resource):
    @inject
    def __init__(self, conf: MyConf):
       self.val = conf.val

    def get(conf: MyConf):
        return {'x': conf.val}, 200


api.add_resource(MyApi, '/myapi')

def configure(binder):
    myConf = MyConf(456)
    binder.bind(
        MyConf,
        to=MyConf(456),
        scope=singleton
    )
    binder.bind(
        MyApi,
        to=MyApi(myConf)
    )

FlaskInjector(app=app, modules=[configure])

app.run(port=555, debug=True)

I'm new to python, actually I don't know if this usage of Flask-Injector is correct, so I'm getting this error when calling the api (myapi) with get method using the browser:

injector.CallError: Call to MyApi.init(conf=<main.MyConf object at 0x0000026575726988>, api=) failed: init() got an unexpected keyword argument 'api' (injection stack: [])

Dabbas
  • 3,112
  • 7
  • 42
  • 75

1 Answers1

1

I was able to solve this with the help of an issue I opened on github, here's the updated working version of the code:

app = Flask(__name__)
app.secret_key = "123"
api = Api(app=app)  

class MyConf():
    def __init__(self, val: int):
        self.val = val

class MyApi(Resource):
    @inject
    def __init__(self, conf: MyConf, **kwargs): # <- here just added **kwargs to receice the extra passed `api` parameter
       self.val = conf.val
       # Don't know if really needed
       super().__init__(**kwargs)

    def get(conf: MyConf):
        return {'x': conf.val}, 200


api.add_resource(MyApi, '/myapi')

def configure(binder):
    myConf = MyConf(456)
    binder.bind(
        MyConf,
        to=MyConf(456),
        scope=singleton
    )
    # No need to bind the resource itself
    #binder.bind(
    #   MyApi,
    #   to=MyApi(myConf)
    #)

FlaskInjector(app=app, modules=[configure])

app.run(port=555, debug=True)
Dabbas
  • 3,112
  • 7
  • 42
  • 75