Introduction
Create Restful APIs in minutes is important when an idea flash in your brain. These APIs maybe not strong or stable, but meaningful to test your greate ideas.
Now, let’s do that in Flask!
You can download full source code in my GitHub here
Create a Python project (Python3 here)
- Make a folder named flask and enter it
- Create a virtual environment for your python project, by running command
python3 -m venv .
in your prompt - Active the virtual envrionment by
source ./bin/activate
By now, the command should look like below:
Install Flask as dependency
Run pip3 install flask
in your prompt
Create app.py and write your code
By now, the file name must be app.py, because we will start the program by Flask cli. Flask cli will load app.py by default.
Copy and paste codes as below:
from flask import Flask, request
app = Flask(__name__)
@app.route("/", methods=["GET"])
def get_index():
return "Hello World"
@app.route("/", methods=["POST"])
def post_index():
d = request.json
s = d['keyword']
if s != None:
return "Your keyword is {0}".format(s)
else:
return "I need your keyword"
Start up the tiny server
Run flask run
in your prompt, and it should look like:
Test your GET API
Open the URL http://localhost:5000 in your browser, e.g. Chrome, and you will get a line on your screen.
Test your POST API (with JSON)
Open Postman, and send a new POST request with a JSON body:
Conclusion
So easy! Python ecosystem is productive, by now, you can write much more logic on the tiny server to test your idea!