1
+ """
2
+ Flask Example - Class Based Flask API using Flask-RESTful
3
+ Level - Intermediate
4
+ Author - [Raj Patra](https:github.com/raj-patra)
5
+ """
6
+
7
+ # Importing flask module in the project is mandatory
8
+ # An object of Flask class is our WSGI application.
9
+ from flask import Flask
10
+
11
+ # Flask-RESTful is an extension for Flask that adds support for quickly building REST APIs.
12
+ from flask_restful import Api , Resource
13
+ from flask_cors import CORS
14
+ from config import Config
15
+
16
+ # Flask constructor takes the name of current module (__name__) as argument.
17
+ app = Flask (__name__ )
18
+
19
+ # It is always a good practice to load the app configuration from a different file.
20
+ app .config .from_object (Config ())
21
+
22
+ # Enabling CORS allows our API to be used from all hosts.
23
+ cors = CORS (app , resources = {r"/*" : {"origins" : "*" }})
24
+
25
+ # Passing our flask app to initialize the Api class from flask_restful.
26
+ api = Api (app )
27
+
28
+
29
+ """
30
+ General practice is to assign the index route
31
+ to atleast one function to avoid 404 error on the
32
+ home route.
33
+
34
+ ‘/’ URL is bound with hello_world() function.
35
+ """
36
+ @app .route ('/' , methods = ['GET' ])
37
+ def index ():
38
+ return "Welcome to Demo-Flask-App" , 200
39
+
40
+
41
+ # Resource classes should be inherited from the Resource class
42
+ class Greeting (Resource ):
43
+ def __init__ (self ):
44
+ # Constructor not necessary for Resource classes.
45
+ pass
46
+
47
+ # All basic HTTP methods already exist in Resource class
48
+ # We over-write the functions after inheriting the Resource class
49
+ def get (self , name : str = None ):
50
+ if name :
51
+ return f"Hello, { name } "
52
+ else :
53
+ return 'Please provide a name "/hello/\{name\}"'
54
+
55
+ # Similarly other functions such as `post`, `put`, `delete`
56
+ # can be overwritten according to the project requirements
57
+
58
+ # Every resource added into `api` becomes an endpoint for flask.
59
+ # Every resources should have a class with basic HTTP methods as its member functions.
60
+ api .add_resource (Greeting , '/hello/<name>' )
61
+
62
+
63
+ if __name__ == '__main__' :
64
+ app .run (use_reloader = True )
0 commit comments