Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Mateen Kiani
Mateen Kiani

Posted on • Originally published atmilddev.com on

     

Create a simple REST API in python using Flask

What actually is a Rest API?

REST is an acronym forREpresentationalStateTransfer. A REST API defines a set of functions which are used to perform requests like GET, POST and PUT and receive responses via HTTP protocol.

This was just a brief intro on what a Rest API is. Let’s create a very simple rest api in python. For this tutorial we will use flask to create our API and the reason for that is its simplicity.

Step 1:

Install Flask using pip

pip install -U Flask
Enter fullscreen modeExit fullscreen mode

pip is a python package manager and is used to install any python package. To know more about pip followthis link.

Step 2:

Create a python file (for example file.py), open it in any text editor and write the following code

fromflaskimportFlaskapp=Flask(__name__)@app.route('/')defhome():return"This is home"app.run(host="127.0.0.1",port="5000")
Enter fullscreen modeExit fullscreen mode

In this code we have imported flask and defined a function named home. Flask contains a built-in wrapper for generating routes in the form of @app.route(‘/’), where @app is the name of the object containing our Flask app. With this decorator present, Flask knows that the next line (sharing the same level of indentation) will be a function containing route logic.

Now run your python file using

python3 file.py
Enter fullscreen modeExit fullscreen mode

or

python file.py
Enter fullscreen modeExit fullscreen mode

On successful execution you will see a message like this in your terminal

Serving Flask app “rest” (lazy loading)

Environment: production

WARNING: This is a development server. Do not use it in a production deployment.

Use a production WSGI server instead.

Debug mode: off

Running onhttp://127.0.0.1:5000/ (Press CTRL+C to quit)

Now when you openhttp://127.0.0.1:5000/ in your browser you will see that your rest api is working.

This is a very simple example. Now if you want to make a Post request you will have to do some more work also most of the rest APIs return json response so we will also cover that as we move ahead.

Rest Api with both GET and POST request

fromflaskimportFlask,requestapp=Flask(__name__)@app.route('/',methods=['GET','POST'])defhome():if(request.method=='GET'):return'Recieved GET request at homepage'else:dataposted=request.datareturnf'recieved a POST request at homepage with{dataposted}'app.run(host="127.0.0.1",port="5000")
Enter fullscreen modeExit fullscreen mode

To test whether post requests are working or not create another python file and name it whatever you want. I have named it request.py and written following code to make HTTP Post request.

importrequestspostData="post data"recieve=requests.post('http://127.0.0.1:5000/',data=postData)print(str(recieve.text))
Enter fullscreen modeExit fullscreen mode

After execution you should get this output

recieved a POST request at homepage with post data

Creating multiple routes

To create another route simply decorate another method with @app.route(‘/[routeAddressHere]’)

fromflaskimportFlask,requestapp=Flask(__name__)@app.route('/',methods=['GET','POST'])defhome():if(request.method=='GET'):return'Recieved GET request at homepage'else:dataposted=request.datareturnf'recieved a POST request at homepage with{dataposted}'@app.route('/about',methods=['GET','POST'])defabout():if(request.method=='GET'):return'Recieved GET request at aboutpage.'else:dataposted=request.datareturnf'recieved a POST request at about page with{dataposted}.'app.run(host="127.0.0.1",port="5000")
Enter fullscreen modeExit fullscreen mode

you can test for multiple routes by either openinghttps://127.0.0.1:5000/about in your browser or by making post request using request.py file as mentioned before.

Return Json response

We can return json response by using jsonify method included in flask package.

fromflaskimportFlask,request,jsonifyapp=Flask(__name__)@app.route('/',methods=['GET','POST'])defhome():if(request.method=='GET'):returnjsonify(output="this is json response")app.run(host="127.0.0.1",port="5000")
Enter fullscreen modeExit fullscreen mode

output:

json response

The postCreate a simple REST API in python using Flask appeared first onMild Dev.

You can mention your queries in the comments section.

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Full stack developer.
  • Location
    Pakistan
  • Work
    Software engineer
  • Joined

More fromMateen Kiani

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp