Wikipedia search app using Flask Framework - Python

Last Updated : 30 Mar, 2026

In this article, we will learn how to build a Flask-based web application that retrieves and displays summaries from Wikipedia based on user input.

Installation

Install flask using the following pip command:

pip install flask

In order to extract the data from Wikipedia, we need Python's Wikipedia library. Install it using:

pip install wikipedia

Create a flask app

Create a file named "app.py", this will be our main file and also create a templates folder to store all the html files.

Directory Structure:

Implementation

Add this code in app.py:

Python
from flask import Flask, request, render_template
import wikipedia

app = Flask(__name__)

@app.route("/", methods=["POST", "GET"])
def home():
    if request.method == "GET":
        return render_template("index.html")
    
    # Process the form submission
    search_query = request.form["search"]
    
    # Fetch data from Wikipedia API
    result = wikipedia.summary(search_query, sentences=2)
    return f"<h1>{result}</h1>"

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

Explanation:

  • @app.route("/", methods=["POST", "GET"]): Defines the URL endpoint and explicitly allows both data retrieval (GET) and data submission (POST).
  • request.method: Checks the incoming HTTP verb to decide whether to show the search form or process a query.
  • request.form["search"]: Accesses the form data sent from the HTML input field named "search".
  • wikipedia.summary(..., sentences=2): Calls the Wikipedia API to return a string containing only the first two sentences of the matching article.
  • app.run(debug=True): Starts the local development server with hot-reloading enabled for easier debugging.

Create a file index.html inside the templates folder and add the following code that provides frontend interface for user interaction: 

HTML
<!DOCTYPE html>
<html>
<head>
    <title>Wikipedia Search</title>
</head>
<body>
    <form method="post">
    <input type="text" name="search">
    <br>
    <button type="submit">Search</button>
    </form>
</body>
</html>

Output:

If we search INDIA in this input tag then the output is:

Code Explanation:

  • method="post": Ensures the form data is sent in the HTTP request body rather than the URL.
  • name="search": Provides the key identifier that the Flask backend uses to extract the user's input.
  • type="submit": Triggers the POST request to the current route when clicked.
Comment