0
0
Flaskframework~5 mins

Namespace concept in Flask

Choose your learning style9 modes available
Introduction

Namespaces help organize your Flask app by grouping related routes and code together. This keeps your project tidy and easier to manage.

You want to separate user-related routes from admin routes in your app.
You have a large app and want to split it into smaller parts for easier development.
You want to reuse a set of routes in different parts of your app or in different apps.
You want to avoid route name conflicts by grouping routes under different namespaces.
Syntax
Flask
from flask import Flask
from flask_restx import Api, Namespace, Resource

app = Flask(__name__)
api = Api(app)

ns = Namespace('example', description='Example operations')

@ns.route('/hello')
class HelloWorld(Resource):
    def get(self):
        return {'message': 'Hello from namespace!'}

api.add_namespace(ns)

Namespaces are created using Namespace from flask_restx.

You add routes to a namespace, then add the namespace to the main API.

Examples
This creates a 'users' namespace with a '/profile' route inside it.
Flask
ns = Namespace('users', description='User related operations')

@ns.route('/profile')
class UserProfile(Resource):
    def get(self):
        return {'user': 'profile data'}
Adds the namespace to the API with a custom URL prefix.
Flask
api.add_namespace(ns, path='/api/users')
Sample Program

This Flask app creates a namespace called 'greet' with a '/hello' route. When you visit '/greet/hello', it returns a greeting message.

Flask
from flask import Flask
from flask_restx import Api, Namespace, Resource

app = Flask(__name__)
api = Api(app)

# Create a namespace for greetings
greet_ns = Namespace('greet', description='Greeting operations')

@greet_ns.route('/hello')
class Hello(Resource):
    def get(self):
        return {'message': 'Hello from greet namespace!'}

# Add namespace to API
api.add_namespace(greet_ns)

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

Namespaces help keep your API routes organized and avoid clutter.

Use namespaces especially when your app grows bigger with many routes.

Remember to add each namespace to the main API with api.add_namespace().

Summary

Namespaces group related routes in Flask apps.

They make large apps easier to manage and understand.

Use Namespace from flask_restx and add it to your API.