gogasca
gogasca

Reputation: 10058

Flask Restful search query

I have migrated my Flask API from Restless to Restful. Flask search query not using filters

Is there a way to perform search queries from client similar to Flask Restless? http://flask-restless.readthedocs.org/en/latest/searchformat.html

They use this format in the curl request:

{"name": <fieldname>, "op": <operatorname>, "val": <argument>}

Upvotes: 6

Views: 10251

Answers (2)

chakib belgaid
chakib belgaid

Reputation: 1

As mentioned in the description of flask-restless, the generated APIs send and receive messages in JSON format, so you have to send the query in format of json,

So for me I took the query string and parsed it in a preprocessor function to add the params in the search filter

def get_many_preprocessor(search_params=None, **kw):
l=[]
for i in request.args.to_dict() : 
    if i == 'q' :
        break 
    else : 
        l.append( {u'name' :str(i) , u'op': u'eq' , u'val':request.args[i]})
if len(l)>0 :
    # print len(l)
    search_params['filters']=l
print search_params 

and then added the preprocessor to my manger

manager.create_api(People, methods=['GET', 'POST', 'DELETE','PATCH'],url_prefix='/',preprocessors={ 'GET_MANY': [get_many_preprocessor],})

The idea is whatever I get a query that contains parameters, I add them manually to the search_params which contains the filters.

You can find more in the official doc.

Good luck and sorry for my bad English

Upvotes: 0

jumbopap
jumbopap

Reputation: 4137

Flask-Restful doesn't magic away your API, since it doesn't have any built-in connection to your database. You'll have to write the logic yourself. Here's one possible way to do it.

class UserSearch(Resource):
    def get(self, search_term):
        results = User.query.filter(User.name.like('%'+search_term+'%')).all()

        # serialize and return items...

api.add_resource(UserSearch, '/users/search/<search_term>')

Upvotes: 8

Related Questions