Tuesday, March 15, 2016

A Simple Rest WebService using Flask

Hi,

I will be doing this PyCharms IDE Community Edition with Python 3.5 version.

First of all you need to install the Flask package.

If you are using CLI , then the command would be

pip install Flask

If you are using PyCharms , then go to File>Settings>Project>Project Interpreter >Click on + button >Search for Flask > Install the package

Once the package is installed, then create a new python file in your project folder. 
I am naming it ekAurRestFile.py

Step 1 : Import the libraries

from Flask import flask,request

Step 2 :  Paste the code . Explanation at :  http://flask.pocoo.org/docs/0.10/quickstart/#quickstart

app = Flask("Rest Sample")

@app.route('/')
def sample_root():
    return 'Welcome'

@app.route('/hello')
def sample_hello():
    if 'name' in request.args:
        return 'Hello ' + request.args['name']
    else:
        return 'Hello Ankit'
if __name__ == '__main__':
    app.run()


Step 3 : Run the server 

If using cli , then navigate to to directory where the python file is present and then type
python ekAurRestFile.py

By the default your app is hosted at http://localhost:5000/

On hitting this url in your broswer , you will see a return as Welcome.

Now try with http://localhost:5000/hello and http://localhost:5000/hello?name=Vijay Dinanath Chahuhan

See the difference.

Happy learning !

No comments:

Post a Comment

 
Tweet