MyInternships.in

Python for Data & Web

Python Flask Basics

Flask is a lightweight Python web framework that lets you build a working web app or API in just a handful of lines, making it a favourite starting point for beginners.


Installing Flask

Flask is a third-party package, so install it with pip inside your project first.

Install Flask
Terminal
pip install flask

A Minimal Flask App

Every Flask app starts with a Flask instance and one or more routes — functions connected to a URL using the @app.route decorator. When someone visits that URL, the matching function runs and its return value becomes the response.

A basic Flask app (app.py)
Python
from flask import Flask

app = Flask(__name__)

@app.route("/")
def home():
    return "Hello from Flask!"

if __name__ == "__main__":
    app.run(debug=True)
Running the app
Terminal
python app.py

With debug=True, Flask auto-reloads whenever you save the file and shows helpful error pages, which is great while learning — just remember to switch it off before deploying to production.

Returning JSON

For an API endpoint, return a Python dictionary and Flask automatically converts it to a proper JSON response using jsonify.

A JSON API endpoint
Python
from flask import Flask, jsonify

app = Flask(__name__)

@app.route("/api/status")
def status():
    return jsonify({"status": "ok", "service": "myinternships"})

Dynamic Routes

You can capture parts of the URL as variables by wrapping a name in angle brackets in the route, letting one function handle many different URLs.

A route with a URL parameter
Python
@app.route("/user/<username>")
def show_user(username):
    return f"Profile page for {username}"

@app.route("/job/<int:job_id>")
def show_job(job_id):
    return jsonify({"job_id": job_id})
💡

Adding <int:job_id> instead of just <job_id> tells Flask to convert the value to an integer automatically and only match numeric URLs.

ℹ️

Flask functions can also handle forms, files, and different HTTP methods like POST using the methods argument in @app.route.

Related Python Topics

Keep learning with these closely related lessons.

Ready to use your Python skills?

Find Python, data science and software internships and fresher jobs across India.

Browse Python Internships