Initial Version
Create your project folder named lr_rest_books_py
.
Create a Virtual Environment
It's a good practice to use a virtual environment to isolate your project dependencies. You can create a virtual environment using venv
module (built-in to Python 3).
python3 -m venv lrFlaskEnv
Caution:
If you're using git or any other version control system, remember to ignore the virtual environment folder.
e.g. in.gitignore
:+ +lrFlaskEnv/
Activate Virtual Environment
Activate the virtual environment. This step is platform-specific.
On Windows:
lrFlaskEnv\Scripts\activate
On macOS and Linux:
source lrFlaskEnv/bin/activate
Manage dependencies
Create a file named requirements.txt
in the root directory of your project. This file will list all the dependencies of your Flask project along with their versions. You can generate this file automatically by using the pip freeze command:
pip3 freeze > requirements.txt
If your virtual environment is set up properly, you should get a empty file named requirements.txt
.
Installation
Install Flask
framework:
pip3 install Flask
After installation, update requirements.txt
:
pip3 freeze > requirements.txt
This command updates the requirements.txt
. It should be something similar to this:
blinker==1.7.0
click==8.1.7
Flask==3.0.2
importlib-metadata==7.0.1
itsdangerous==2.1.2
Jinja2==3.1.3
MarkupSafe==2.1.5
Werkzeug==3.0.1
zipp==3.17.0
Create main.py:
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/ping')
def ping():
return jsonify({"message": "pong"})
if __name__ == '__main__':
app.run(debug=True)
Run the program like this:
python3 main.py
You will get result lines like below:
* Serving Flask app 'main'
* Debug mode: on
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
* Running on http://127.0.0.1:5000
Press CTRL+C to quit
* Restarting with stat
* Debugger is active!
* Debugger PIN: nnn-nnn-nnn
Your API server is runnong on port 5000 now.
Note:
You may also choose to use theflask
command.flask --app main run # debug mode off flask --app hello run --debug # debug mode on
And you don’t need the
__main__
part if you’re using theflask
command.if __name__ == '__main__': app.run(debug=True)
Try to hit the endpoint /ping
with curl
command:
curl http://localhost:5000/ping
It shows:
{
"message": "pong"
}
Nice! Your server is doing well.