Views and Routing

Views are the functions/classes where you specify the routes and implement the main logic.

Function Based Views

Function based views are very simple to implement.

 
                
                    @app.route('/home') 
                    def home(request):  
                        return JsonResponse({'data':'hello world'},Status.HTTP_200_OK)
                    
                
            

You can also specify the specific allowed methods for a particular view.

                
                    @app.route('/home', allowed_methods=['GET','POST']) 
                
            

Class Based Views

A class based view is also supported in tiny-api.

                
                    @app.route('/home')
                    class Home:
                        ALLOWED_METHODS = ['GET']
                        
                        def get(self,request):
                            return JsonResponse({'data':'hello world'},Status.HTTP_200_OK)

                
            

Requests

The request is an object of class Request which is subclassed from webob.Request . Access the elements from request:-

Example: Access the bearer token as :-


                bearer = request.bearer
            
(this returns a bearer token passed from the client if present else returns None)

Access the Post data:-

                
                    username = request.POST.get['username']
                
            

Access the Query string:-

                
                    username = request.params.get['username']
                
            

Visit here for more info:- Webob Request

Json Response

JsonResponse helps to send back the response in JSON format which can be consumed in the frontend part.

You can import it as :
                
                    from tiny_api.Responses import json_response
                
            
Return JsonResponse as :-
                
                    return JsonResponse({'data':'data'},status_code)
                
            

Middleware

A middleware is an application that processes the incoming/outgoing requests and responses.
You can add your custom middleware and tweak the requests and responses as per your requirements.
Example:-

                
                    class CustomMiddleware(Middleware):
                        def process_request(self, request):
                            request.add_param("hey","there")
                            # add_param allows you to add custom elements to the request object

                    app = Tinyapi()
                    app.add_middleware(CustomMiddleware)

                
            

To add your custom middleware, you have to inherit the Middleware class and overide the process_request and
process_response methods.

JSON Web Tokens

Since tiny-api encourages to have client and server separated from each other, jwt tokens are best suited for such applications.
Tiny-api has inbuilt jwt token support. It uses pyjwt package to provide token authentication and uses 'HS256' algorithm.
Create/decode tokens in tiny-api as:-

                    
                        from tiny_api.jwt_tokens import create_access_token, create_refresh_token, decode_access_token
                        
                        # creates an access token
                        access_token = create_access_token(user_id = 1, username = 'hellouser', seconds = 1800, secret_key = None)

                        # creates a refresh token, return an object of class uuid.UUID
                        refresh_token = create_refresh_token()

                        # decodes the access token, returns a boolean value and the actual data
                        is_valid, data = decode_access_token(data = access_token, secret_key = None)

                    
                

The 'decode_access_token' returns two values. The first value is a boolean and it specifies either the token is valid or not.
The second value is the actual data. If the token is invalid then instead of returning the data it returns an exception object.
Hence always check if the token is valid or not before using the data.

Secret Key

But what is this secret key?? Well, its a secret key :) :) . By default the secret key is 'myappsecret123abc' .
However, this is not secure at all. Hence, it is recommended to add your own secret key. For this, create a .env file and add this:-

                        
                            SECRET_KEY=your_secret_key
                        
                    
(Replace your_secret_key with your secret key.)

Authentication

Check if the request is authenticated or not, i.e if the requets contains a valid bearer token or not.

                    
                        from tiny_api.auth import is_authenticated
                        
                        # return a boolean value
                        is_auth = is_authenticated(request)
                    
                
You can also make a view accessible only by the authenticated users. For this:-
                    
                        from tiny_api.auth import authenticated

                        @app.route('/authenticated_view')
                        @authenticated
                        def authenticated_view(request):
                        return JsonResponse({'data':'hello world'})
                    
                

Get Env Vars

Tiny-api provides a very easy way to access the env variables.

                    
                        from tiny_api.get_env_var import get_env_vars

                        data = get_env_vars('SECRET_KEY',default = 'my_secret_key')
                        # it returns the SECRET_KEY's value from .env file else returns the default value.
                    
                

Templates

Tiny-api supports template rendering using Jinja2 . (However, not recommended, instead use ajax or React/Vue and keep frontend and backend separate).
For this create template directory. Inside it create index.html file. Inside index.html copy the following:-

                
                    <html>
                        <header>
                            <title>{{ title }}</title>
                        </header>

                        <body>
                            hello {{ name }}
                        </body>
                    </html>
                
            

Now, create a view.

                
                    from Responses import TemplateResponse

                    app = Tinyapi()

                    @app.route('/template_view')
                    def template_view(request):
                        return TemplateResponse(app=app,'index.html',context = {'title':'page title','name':'my name'})

                
            

Now run the app and you will see the magic :) :) .

Static Files

Tiny-api also supports static files. It serves the static files using whitenoise.
Create a new directory named static and create a sub directory named css.
Inside this create main.css file. Create index.html file inside the template directory and copy the following:-

                
                    <html>
                        <header>
                            <title>{{ title }}</title>
                            <link href="/static/css/main.css" type="text/css" rel="stylesheet">
                        </header>
                    
                        <body>
                            hello {{ name }}
                        </body>
                    </html>
                
            

Now inside main.css copy folowing and save.

                
                    body {
                        background-color:red;
                    }
                
            

Now create a view as defined in the Template section above and visit 127.0.0.1:8000/template_view page to see the magic.

Database Support and ORM

Tiny-api is compatible with both relational(eg:-sqlite, postgresql) and non-relational (eg:-mongodb) databases.
For SQL database you can use the packages like sqlalchemy and marshmallow-sqlalchemy.
For Mongodb, you can use the package like pymongo.