๐Ÿš€ Getting Started with Flask: A Beginner's Guide

Manav RastogiManav Rastogi
3 min read

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

๐Ÿ”— Github/ManavRastogi03

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.

0
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."