Your first web API with Flask
Build a tiny web API in Python with Flask on Ubuntu: a virtual environment, one route, and a curl call that returns your text in capitals.
Build a tiny web API in Python with Flask on Ubuntu: a virtual environment, one route, and a curl call that returns your text in capitals.
In plain words
A web API is a counter in a shop. You do not walk into the kitchen: you hand over a note with a question (a web address) and a program behind the counter hands back an answer in a fixed format. Our counter takes a word and gives it back in CAPITALS.
Try it yourself
Do this in a terminal on Ubuntu. A folder of your own keeps it apart from your other work.
mkdir -p ~/api && cd ~/api
python3 -m venv .venv
. .venv/bin/activate
pip install flask
A virtual environment (.venv) is a private box of Python libraries for this project only. Now create app.py (use the editor, or nano app.py):
from flask import Flask, jsonify, request
app = Flask(__name__)
@app.get("/upper")
def upper():
text = request.args.get("text", "")
return jsonify({"original": text, "upper": text.upper()})
if __name__ == "__main__":
app.run(host="localhost", port=8000)
Run it, then open a second terminal and ask it a question:
python app.py
# second terminal
curl "http://localhost:8000/upper?text=hello%20world"
You should see {"original":"hello world","upper":"HELLO WORLD"}. Stop the server with Ctrl+C.
A step further
Read the code line by line. @app.get("/upper") says: when someone asks for the address /upper, run this function. request.args.get("text", "") reads ?text=... from the address, and "" is what you get when it is missing. jsonify turns a Python dictionary into JSON.
Try two changes: add a second route /length that returns how many characters the text has, and answer with an error when there is no text:
if not text:
return jsonify({"error": "text is required"}), 400
The number 400 is the status code: you asked wrongly.
How it works in real projects
What you ran is a development server: fine for learning, not for visitors. In production a real server program runs the app, a service manager keeps it alive, and a proxy sits in front of it.
Never run Flask with debug=True on an address other people can reach: its debugger lets a visitor run code on your machine. That is why this example listens on localhost (this machine only). To let other computers reach it you would bind a public address instead, and only after putting a sign-in in front of it.