0
0
Flaskframework~30 mins

Namespace concept in Flask - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Flask Namespace Concept
📖 Scenario: You are building a simple Flask web app that organizes routes using namespaces to keep the code clean and modular.
🎯 Goal: Create a Flask app with two namespaces: user_ns for user-related routes and product_ns for product-related routes. Each namespace will have one route that returns a simple message.
📋 What You'll Learn
Create a Flask app instance
Create two namespaces named user_ns and product_ns
Add one route to each namespace returning a simple string message
Register both namespaces with the Flask app
💡 Why This Matters
🌍 Real World
Namespaces help organize large Flask APIs by grouping related routes, making the code easier to maintain and understand.
💼 Career
Understanding namespaces is important for backend developers working with Flask REST APIs to build scalable and modular web services.
Progress0 / 4 steps
1
Create Flask app and namespaces
Import Flask and Namespace from flask_restx. Create a Flask app instance called app. Then create two namespaces called user_ns and product_ns with descriptions 'User operations' and 'Product operations' respectively.
Flask
Need a hint?

Use app = Flask(__name__) to create the app. Use Namespace('name', description='desc') to create namespaces.

2
Add routes to namespaces
Add a route /info to user_ns that returns the string 'User info page'. Add a route /list to product_ns that returns the string 'Product list page'. Use the @user_ns.route('/info') and @product_ns.route('/list') decorators and define functions user_info() and product_list() respectively.
Flask
Need a hint?

Use the @namespace.route('path') decorator and define a function returning the string message.

3
Create API and add namespaces
Import Api from flask_restx. Create an Api instance called api using the app. Add the namespaces user_ns and product_ns to the api using api.add_namespace().
Flask
Need a hint?

Create api = Api(app) and add namespaces with api.add_namespace(namespace).

4
Run the Flask app
Add the standard Flask app run block: if __name__ == '__main__': and inside it call app.run(debug=True) to start the server in debug mode.
Flask
Need a hint?

Use the standard Flask run block to start the app with debug mode enabled.