Practical Guide: Building a Mock Server with Python and Flask

Mocking involves simulating API endpoints.

In API testing, mocking is used when certain interfaces are difficult or impossible to construct or retrieve. A mock endpoint can be used to replace these real ones.

2. Typical Use Cases for Mocking

  • When dependent APIs are not yet imlpemented
  • When dependent APIs respond slowly
  • Simulating various error scenarios

3. Benefits of Using Mocks

  • Eliminates dependencies on external services, allowing tests to run independently
  • Enables controlled simulation of error conditions that are hard to trigger naturally
  • Allows team members to work in parallel without waiting for upstream services

4. Three Common Approaches to Implement Mocking

The core idea behind implementing mocks is to set up a mock server that provides simulated endpoints:

  • Use third-party platforms like Moco
  • Develop your own mock service
  • Utilize framework-based solutions such as Python + Flask

01. Creating a Mock Server with Python and Flask

Flask is a lightweight web application framework written in Python. It allows developers to quickly build web applications.

Environment Setup

  • Install Flask: Use pip to install: pip install Flask
  • Verify Installation: Run flask --version in the terminal to confirm it's installed correctly

Example Scenarios

Scenario 1: Simulate a login endpoint

  • Successful login should return HTTP status 200 with JSON payload: ``` {"status": 200, "msg": "Login successful!", "code": 10000, "token": "xxxx123123123"}

  • Failed login should return: ``` {"status": 100, "msg": "Invalid username or password!", "code": 99999}

    
    

Problem: The actual login endpoint hasn't been developed yet — how do we proceed?

Implementation Steps:

  1. Create a Flask app
  2. Run the script like any standard Python program
  3. Access via browser at http://127.0.0.1:5000/login
from flask import Flask, jsonify

app = Flask(__name__)

@app.route("/login", methods=["GET", "POST"])
def login():
    response_data = {
        "status": 200,
        "msg": "Login successful!",
        "code": 10000,
        "token": "xxxx123123123"
    }
    return jsonify(response_data)

@app.route("/login/eln", methods=["GET"])
def elogin():
    return "error page", 404, {"Content-Type": "application/json"}

if __name__ == "__main__":
    app.run()

Scenraio 2: Login validation with credentials

  • Valid credentials: username = admin, password = 123456
  • Returns success message
  • Otherwise returns an error
  • Request body uses form data format
from flask import Flask, request

app = Flask(__name__)

@app.route("/login", methods=["POST"])
def login():
    username = request.form.get("username")
    password = request.form.get("password")

    if username == 'admin' and password == '123456':
        return {
            "status": 200,
            "msg": "Login successful!",
            "token": "xxxx123123123"
        }
    else:
        return {
            "status": 100,
            "msg": "Invalid username or password!"
        }

if __name__ == "__main__":
    app.run()

Tags: python Flask API Testing Mock Server web development

Posted on Thu, 08 Oct 2026 16:35:16 +0000 by brokeDUstudent