Python Flask web server tutorial from the scratch

CK CK 3788 
Created at  
623 0 0

Flask is a feature in the Flask web framework (a popular micro web framework for Python). Flask-Flash is used to display flash messages to users. Flash messages are typically used to provide feedback to users, such as notifications about the success or failure of an operation.

Here's a simple Flask web server in Python with a basic API. This example will create a server that can handle GET and POST requests.

 

Step 1: Install Flask

If you don't have Flask installed, you can install it using pip:

pip install Flask

 

Step 2: Create the Flask Web Server

Create a new Python file (e.g., app.py) and add the following code:

from flask import Flask, request, jsonify

app = Flask(__name__)

# Define a route for a simple GET request
@app.route('/api/hello', methods=['GET'])
def hello_world():
    return jsonify(message="Hello, World!")

# Define a route for a simple POST request
@app.route('/api/data', methods=['POST'])
def get_data():
    data = request.get_json()
    return jsonify(received_data=data)

if __name__ == '__main__':
    app.run(debug=True)

Explanation

  1. Importing Flask and necessary modules:

    from flask import Flask, request, jsonify
    
  2. Initialize the Flask application:

    app = Flask(__name__)
    
  3. Define a route for a GET request:

    @app.route('/api/hello', methods=['GET'])
    def hello_world():
        return jsonify(message="Hello, World!")
    
  4. Define a route for a POST request:

    @app.route('/api/data', methods=['POST'])
    def get_data():
        data = request.get_json()
        return jsonify(received_data=data)
    
  5. Run the application:

    if __name__ == '__main__':
        app.run(debug=True)
    

 

Running the Server

To run the server, navigate to the directory where your app.py is located and execute the following command:

python app.py

The server will start running on http://127.0.0.1:5000/.

 

Testing the API

You can test the API using tools like curl, Postman, or simply your browser.

  1. Testing the GET request:

    curl http://127.0.0.1:5000/api/hello
    

    You should see the following response:

    {
        "message": "Hello, World!"
    }
    
  2. Testing the POST request:

    curl -X POST http://127.0.0.1:5000/api/data -H "Content-Type: application/json" -d '{"name": "Levi", "age": 18}'
    

    You should see the following response:

    {
        "received_data": {
            "name": "Levi",
            "age": 18
        }
    }
    

This basic setup can be extended to include

Tags Flash Web Framework Flash Web Server Flask Facebook X
Comments 0
Similar posts
  1. Python Flask with simple HTML files to server web pages along with API
    927
  2. Dynamic DNS Made Easy: Building a Python-Based Solution
    795
  1. Python code to convert PDF file to Excel Spreadsheet
    701
  2. Python script to list files on your Google Drive and download one of them
    941
  3. Coinbase Python API - Basic Example
    462
  4. AWS Lambda Code Example based on Python
    333
  5. Python code using GPU on CentOS with AWS
    1,252
  6. Video Scence Detection with PySceneDetect
    2,323
  7. Python Audio Separation Libraries allowing you to isolate individual tracks
    1,446
  8. Python Version Control for Library Compatibility with pyenv - Downgrading/Upgrading Python Version
    908
  9. Deleting a specific user voice from the original audio track with Python
    549
  10. Creating an MR from the original MP3 audio in Python - Deleting Voice Track from Audio File
    441
  11. Creating mp3 audio file based on the text input with Python
    465
  12. Implementing Text To Speech / Audio with Python3 and pyttsx3
    355
  13. Building Initial Virtual Environment at Python - The first step you should do for Python Programming
    559
  14. Python Simplified Assignment Operators
    533
  15. Trackback module used for Python Threading debugging
    843
  16. Simple Web Server based in Python
    373
  17. Thread Implementation in Python
    509
  18. A shell script that activates a Python virtual environment and then runs a specific Python script
    743
  19. Learning about Python Multiprocessing Technique
    592
  20. Simple Example to get the total number of records in BigQuery with Python
    666
  21. Using BigQuery in Python
    412
  22. Python Web Programming based on Django from the Scratch
    374
  23. Flink with Python: Core Concepts, Kafka Integration, and Architectural Trade-offs
    188
  24. How do I determine the client IP type in Python - IPv4 or IPv6
    763
  25. Predicting Buyer Preferences with PyTorch: A Deep Learning Approach
    1,233
  26. PyTorch example to Forcast Stock Price based on 10 days Dataset
    651
  27. Implementing a Versatile DNS Server in Python: Handling A, AAAA, CNAME, and TXT Records
    1,073
  28. Milvus & FAISS: Decoding Their ML Synergy
    279
  29. Save clustering result (aka dictionary) in JSON and Reuse loaded result
    378
  30. Forecasting with Linear Regression and KNN Regression in Python
    926
Recently updated
  1. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    42
  2. Why SPF and DKIM Are Essential for Linux Email Servers?
    36
  3. How do I create animated background for Google Meet?
    20,996
  4. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    251
  5. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    94
  6. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    157
  7. Array of arguments passed to script in PHP
    90
  8. Invalid Auction Storms in Ad Tech
    98
  9. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    202
  10. The Two Clocks of Ad Server Architecture
    70
  11. Frequency Cap Architecture Overview
    515
  12. Collecting Proof-of-Play from 100,000 Screens
    146
  13. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    288
  14. What is RedisVL?
    109
  15. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    231
  16. TPU & GPU Cluster Management Tools
    245
  17. The Concept of Scaffolding in AI Agents
    234
  18. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    583
  19. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    259
  20. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    339
  21. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    202
  22. Machine Learning: Training vs. Ranking
    222
  23. The Continuous Learning Machine: Designing a Loop That Actually Turns
    222
  24. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    195
  25. Designing a Data Curation System Around a Vector Database
    221
  26. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    256
  27. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    656
  28. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    196
  29. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    219
  30. Understanding Data Lineage
    262