pavan subhash
pavan subhash

Reputation: 378

Error: While calling Flask API (Json Decodeerror)

Hi I am new to exposing Ml models as flask API. Below is my code:

import numpy as np
from nltk.corpus import wordnet
from nltk.stem.wordnet import WordNetLemmatizer
import re
from sklearn.externals import joblib
import warnings

warnings.filterwarnings('ignore')
from flask import Flask, jsonify, request


app = Flask(__name__)

@app.route("/glcoding", methods=['POST'])    
def mylemmatize(token):
    lmtzr = WordNetLemmatizer()
    lemmas = {}
    lemma = None
    if not token in lemmas:
         lemma = wordnet.morphy(token)

    if not lemma:

         lemma = token

    if lemma == token:
         lemma = lmtzr.lemmatize(token)

    lemmas[token] = lemma

    return lemmas[token]




def cleanmytext(text):
   words = map(mylemmatize,text.lower().split())
   return ' '.join(words)



def glcoding():
    if request.method == 'POST':
         json_data = request.get_json()         
         data = pd.read_json(json_data, orient='index') 

         data['Invoice line item description'] = data['Invoice line item description'].apply(cleanmytext)

    return jsonify(data)

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

With the below code I am calling the API:

from flask import Flask, jsonify, request
import requests, json



 BASE_URL = "http://127.0.0.1:5000"

  data = '{"0":{"Vendor Number": "166587","Invoice line item description":"Petrol charges with electricity"}}'

  response = requests.post("{}/glcoding".format(BASE_URL), json = data)

  response.json()

I am getting a error as mentioned below:

Traceback (most recent call last):
  TypeError: mylemmatize() takes exactly 1 argument (0 given)
    127.0.0.1 - - [16/Mar/2018 14:31:51] "POST /glcoding HTTP/1.1" 500 -

The above code is working fine when I am not exposing it as an API. But it is throwing up an error only when called from an API. Please help

Upvotes: 0

Views: 84

Answers (2)

sewi
sewi

Reputation: 71

You decorated the wrong method with the app.route() decorator. Just move the decorator above the glcoding() method and everything should be working.

Upvotes: 2

Mekicha
Mekicha

Reputation: 851

You defined your request handler mylemmatize(token) to take a variable called token but you route is not aware of that and so does not pass your data to the request handler. Change your route from :

@app.route("/glcoding", methods=['POST'])

to this instead:

@app.route("/glcoding/<token>", methods=['POST'])

See the doc on variable rule for more info.

Also if you do not need to pass the token as a variable, then you need to remove it from your mylemmatize function definition.

Upvotes: 0

Related Questions