๐ Getting Started with Flask: A Beginner's Guide

Flask is a lightweight and powerful web framework for Python, making it easy to build web applications and APIs. If you're new to Flask, this guide will help you understand the basics, key features, and hands-on projects to get started! ๐๏ธ
๐ฅ Why Use Flask?
Flask is popular because:
โ Lightweight: Minimal setup required, yet highly scalable.
โ Easy to Learn: Simple syntax makes it beginner-friendly.
โ Flexible: Allows you to structure your application as needed.
โ Great for APIs: Perfect for building RESTful web services.
โ Massive Community: Tons of tutorials and support available.
๐ฏ Flask Basics
To start using Flask, you need to install it first:
pip install flask
Then, create a simple Flask app:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return "Hello, Flask!"
if __name__ == '__main__':
app.run(debug=True)
Flask(__name__)
: Creates an app instance.@app.route('/')
: Defines the home route.app.run
(debug=True)
: Runs the application.
Run the script, and visit http://127.0.0.1:5000/
in your browser. ๐
๐๏ธ Project 1: Building a Weather Data API with Flask
๐ GitHub Repository
Let's create a Flask API that fetches, processes, and provides weather data in multiple formats (CSV, Excel, XML).
๐น Steps to Build the API
1๏ธโฃ Fetch Weather Data ๐ก
from fetch_data import fetch_weather_data
raw_data = fetch_weather_data()
2๏ธโฃ Process Data ๐งน
from process_data import process_weather_data
processed_data = process_weather_data(raw_data)
3๏ธโฃ Convert & Save Data ๐
from convert_data import convert_to_csv, convert_to_excel, convert_to_xml
csv = convert_to_csv(processed_data)
excel = convert_to_excel(processed_data)
xml = convert_to_xml(processed_data)
4๏ธโฃ Create Flask Endpoints ๐
from flask import Flask, send_file, jsonify
app = Flask(__name__)
@app.route('/get_weather_data', methods=['GET'])
def get_weather_data():
return jsonify({'message': 'Weather data processed successfully'})
@app.route('/download_csv', methods=['GET'])
def download_csv():
return send_file("data.csv", as_attachment=True)
if __name__ == "__main__":
app.run(debug=True)
๐๏ธ Project 2: Building a Machine Learning API with Flask
๐ GitHub Repository
๐ Github/ManavRastogi03/Proj2
Now, let's create a Flask API that trains a machine learning model and makes predictions.
๐น Steps to Build the API
1๏ธโฃ Train & Save the Model ๐๏ธโโ๏ธ
import joblib
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
import pandas as pd
import os
MODEL_PATH = "model.pkl"
ONLINE_DATA_PATH = 'data/online_data.csv'
# Fetch dataset
data = pd.read_csv(ONLINE_DATA_PATH)
X = data.drop(columns=['Outcome'])
y = data['Outcome']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=43)
# Train model
model = RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X_train, y_train)
# Evaluate model
accuracy = accuracy_score(y_test, model.predict(X_test))
print(f"Model Accuracy: {accuracy:.4f}")
# Save model
joblib.dump(model, MODEL_PATH)
print(f"Model saved to {MODEL_PATH}")
2๏ธโฃ Load Model & Make Predictions ๐
from flask import Flask, request, jsonify
import joblib
import numpy as np
app = Flask(__name__)
model = joblib.load(MODEL_PATH)
@app.route('/predict', methods=['POST'])
def predict():
try:
data = request.get_json()
input_data = np.array([data[feature] for feature in ['Pregnancies', 'Glucose', 'BloodPressure', 'SkinThickness', 'Insulin', 'BMI', 'DiabetesPedigreeFunction', 'Age']]).reshape(1, -1)
prediction = model.predict(input_data)
return jsonify({'prediction': int(prediction[0])})
except Exception as e:
return jsonify({'error': str(e)}), 400
if __name__ == "__main__":
app.run(debug=True)
๐ฏ Key Takeaways
โ Flask is simple yet powerful for building web applications.
โ Creating APIs with Flask is easy and intuitive.
โ You can integrate Flask with data processing, file handling, and machine learning models.
โ Flask is perfect for learning and real-world applications.
Subscribe to my newsletter
Read articles from Manav Rastogi directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Manav Rastogi
Manav Rastogi
"Aspiring Data Scientist and AI enthusiast with a strong foundation in full-stack web development. Passionate about leveraging data-driven solutions to solve real-world problems. Skilled in Python, databases, statistics, and exploratory data analysis, with hands-on experience in the MERN stack. Open to opportunities in Data Science, Generative AI, and full-stack development."