<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Devang Mistry on Medium]]></title>
        <description><![CDATA[Stories by Devang Mistry on Medium]]></description>
        <link>https://medium.com/@DevangMstryls?source=rss-4240a83c544e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*O2u1J7SmqChaNlak7G8D_g.jpeg</url>
            <title>Stories by Devang Mistry on Medium</title>
            <link>https://medium.com/@DevangMstryls?source=rss-4240a83c544e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 00:34:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@DevangMstryls/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Creating a Flask-based RESTful API for Reliable Production Use]]></title>
            <link>https://medium.com/@DevangMstryls/creating-a-flask-based-restful-api-for-reliable-production-use-f838cf690fe7?source=rss-4240a83c544e------2</link>
            <guid isPermaLink="false">https://medium.com/p/f838cf690fe7</guid>
            <category><![CDATA[flask-restful]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[sqlite3]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[rest-api]]></category>
            <dc:creator><![CDATA[Devang Mistry]]></dc:creator>
            <pubDate>Thu, 13 Apr 2023 15:46:04 GMT</pubDate>
            <atom:updated>2023-04-13T15:46:04.147Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9x5vP3JfT2nR1YCF-SHdgg.png" /></figure><h4>Introduction</h4><blockquote>This tutorial is aimed at beginners in Flask who want to use it for creating a REST-based API app.</blockquote><p>In this tutorial we will,</p><ol><li>Create a Flask-based REST application — ready for production use — that serves as a backend for a blog</li><li>Explore various concepts like Blueprints and Middlewares.</li><li>Implement data validation and sanitizing using <a href="https://marshmallow.readthedocs.io/en/stable/index.html">Marshmallow</a>.</li></ol><h4>Installing Flask and <a href="https://flask-restful.readthedocs.io/en/latest/">Flask-RESTFul</a></h4><p>Before we can install Flask and create our application, we need to setup a python virtual environment for our application.</p><pre>$ mkdir flask-blog-api<br>$ cd flask-blog-api<br><br>$ virtualenv -p python3.7 ./flask-blog-api-venv<br>created virtual environment CPython3.7.9.final.0-64 in 399ms<br>  creator CPython3Posix(dest=/Users/devang/path/to/workdir/flask-blog-api/flask-blog-api-venv, clear=False, no_vcs_ignore=False, global=False)<br>  seeder FromAppData(download=False, pip=bundle, setuptools=bundle, wheel=bundle, via=copy, app_data_dir=/Users/devang/Library/Application Support/virtualenv)<br>    added seed packages: pip==22.2.2, setuptools==65.3.0, wheel==0.37.1<br>  activators BashActivator,CShellActivator,FishActivator,NushellActivator,PowerShellActivator,PythonActivator</pre><p><em>I prefer to call my virtual environments with their project names appended by venv. When the virtual environment is activated, the full name is visible in the terminal application. This is helpful when working on multiple Python projects.</em></p><p>Let’s activate the environment</p><pre>$ source flask-blog-api-venv/bin/activate</pre><p>Now once our environment is activated, we can install Flask and Flask-RESTful</p><pre>(flask-blog-api-venv) $ pip3 install flask Flask-RESTful</pre><p>This will install the two packages and some other packages that they both depend upon.</p><p>We can now start building our application.</p><h4>Building the application</h4><p>Since Flask is a very lightweight web framework, we can create a basic REST API by just making a file called app.py with the following code in it:</p><pre>### flask-blog-api/flask_blog_api/app.py<br><br><br>from flask import Flask<br>from flask_restful import Resource, Api<br><br><br>app = Flask(__name__)<br>api = Api(app) # pass the Flask app instance to Api from flask_restful<br><br><br>class HelloWorld(Resource):<br>    def get(self):<br>        return {&#39;hello&#39;: &#39;world&#39;}<br><br>api.add_resource(HelloWorld, &#39;/&#39;)<br><br><br>if __name__ == &#39;__main__&#39;:<br>    app.run(debug=True)</pre><h4>Declaring and reading the environment variables from a config file</h4><p>We will now create a .env file to define our environment variables. In the project root directory, create a folder called flask_blog_api. Inside that folder, create a file called .env and add the following content:</p><pre>### flask-blog-api/flask_blog_api/.env<br><br>export ENV=&#39;local&#39;;</pre><p>Also move the app.py file into the flask_blog_api folder from the root of the project. The file structure now should look like this:</p><pre>- flask-blog-api-venv/<br>- flask_blog_api/<br> - .env<br>  - app.py </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*GFeoVv9LdIP5DG6yHfsr-g.png" /></figure><p><strong>Reading the env variables and loading into our app</strong></p><p>In order to read our environment variables defined in the .env file, we need to install another package called python-dotenv so that we can load it into our app and make them available to be used.</p><pre># install python-dotenv<br>(flask-blog-api-venv) $ pip3 install python-dotenv</pre><p>In the app.py file, put the following contents:</p><pre>### flask-blog-api/flask_blog_api/app.py<br><br><br>from flask import Flask<br>from flask_restful import Api, Resource<br>from dotenv import load_dotenv<br><br>load_dotenv(verbose=True)<br><br>env = os.getenv(&#39;ENV&#39;)<br><br>print(env)<br><br>app = Flask(__name__)<br>api = Api(app) # pass the Flask app instance to Api from flask_restful<br><br>class HelloWorld(Resource):<br>    def get(self):<br>        return {&#39;hello&#39;: &#39;world&#39;}<br><br>api.add_resource(HelloWorld, &#39;/&#39;)<br><br>if __name__ == &#39;__main__&#39;:<br>    app.run(debug=True)</pre><h4>Creating blueprints</h4><p><strong>But what is a Blueprint and why do I need it?</strong></p><p>According to the official <a href="https://flask.palletsprojects.com/en/2.2.x/tutorial/views/#create-a-blueprint">Flask docs</a>,</p><blockquote>A blueprint is a way to <strong>organize</strong> a group of <strong>related views</strong> and other code.</blockquote><blockquote>Rather than registering views and other code <em>directly</em> with an application, they are registered with a blueprint. Then the blueprint is registered with the application when it is available in the factory function.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*NdWYfYUe6mLLWaUZVpMfDQ.png" /></figure><p>Out REST API for blog will have 2 blueprints, one for authentication and one for posts.</p><p>Let’s create our first blueprint for authentication.</p><p><strong>Authentication blueprint</strong></p><pre>bp = Blueprint(&#39;**blueprint-name**&#39;, **name**, url_prefix=&#39;**/blueprint-url-prefix**&#39;)</pre><p>Just like our Flask app object defined above had __name__ as an argument, we will have to pass __name__ as the second argument to the Blueprint object.</p><p>The url_prefix defined will be prepended to all of our API routes that we will define.</p><p>So if any API route is /login and if that is registered with our auth_bp blueprint then the final callable url will be /auth/login.</p><p>Make sure to add the above line before the call to Api and pass the auth_bp blueprint to it. So the code should now look like this:</p><pre>### flask-blog-api/flask_blog_api/app.py<br><br><br># ... previous code<br><br>app = Flask(__name__)<br><br># define all your blueprints here<br>auth_bp = Blueprint(&#39;auth&#39;, __name__, url_prefix=&#39;/auth&#39;)<br>api = Api(auth_bp)</pre><p>Now as our blueprint is ready, let’s add some routes to it.</p><p><strong>Adding resources (API routes)</strong></p><p>We’ll define our resources in a different file from our main file. So let’s create a new file and add our first resource. Create a file called auth_resources.py file under resources directory and put the following contents in it:</p><pre>### flask_blog_api/resources/auth_resources.py<br><br><br>from flask_restful import Resource<br><br>class RegisterRoute(Resource):<br>    def post(self):<br>        return {<br>            &#39;success&#39;: True,<br>        }, 200</pre><p>Now we need to register the RegisterRoute resource with url(https://medium.com/s). Add the following contents in app.py file:</p><pre>### flask-blog-api/flask_blog_api/app.py<br><br><br># ... above code<br><br>api = Api(auth_bp)<br><br># Register Routes<br>api.add_resource(RegisterRoute, &#39;/register&#39;)<br><br># ... below code</pre><p>Send a post request to <a href="http://127.0.0.1:5001/auth/register">http://127.0.0.1:5001/auth/register</a> via Postman, it should return:</p><pre>{<br>    &quot;success&quot;: true<br>}</pre><h4>Integrating with a Database</h4><p>For the simplicity of this post, we will use SQLite as our DB. Let’s create our first table for users.</p><p>Create a file at flask-blog-api/database/schema.sql and put the following contents in it:</p><pre>--- flask-blog-api/database/schema.sql<br><br><br>DROP TABLE IF EXISTS users;<br><br>CREATE TABLE users (<br>    id INTEGER PRIMARY KEY AUTOINCREMENT,<br>    name TEXT NOT NULL,<br>    email TEXT NOT NULL,<br>    password TEXT NOT NULL,<br>  token TEXT NOT NULL,<br>    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP<br>);<br><br>DROP TABLE IF EXISTS posts;<br><br>CREATE TABLE posts (<br>    id INTEGER PRIMARY KEY AUTOINCREMENT,<br>    title TEXT NOT NULL,<br>    content TEXT NOT NULL,<br>    is_published BOOLEAN DEFAULT NULL,<br>    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP<br>);</pre><p>Now, let’s initialize our database. Create a file at flask-blog-api/scripts/init_db.py and put the following contents in it:</p><pre>### flask-blog-api/scripts/init_db.py<br><br><br>import sqlite3<br><br>connection = sqlite3.connect(&#39;database/blog.db&#39;)<br><br>with open(&#39;database/schema.sql&#39;) as f:<br>    connection.executescript(f.read())<br><br>connection.close()</pre><p>Running this python script will create a database at database/blog.db and create the users table in it.</p><p>Now, let’s quickly make a helper file to get the database connection. Create a file at flask-blog-api/flask_blog_api/helpers/database.py and put the following content in it:</p><pre>### flask-blog-api/flask_blog_api/helpers/database.py<br><br><br>import sqlite3<br><br>def get_db_connection():<br>    db_conn = sqlite3.connect(&#39;../database/blog.db&#39;)<br>    db_conn.row_factory = sqlite3.Row<br>    return db_conn</pre><p>As our database is ready to use, let’s add some more functionality to our RegisterRoute resource.</p><pre>### flask-blog-api/flask_blog_api/resources/auth_resources.py<br><br><br>from flask_restful import Resource<br>from flask import request<br><br>class RegisterRoute(Resource):<br>    def post(self):<br>        try:<br>            payload = request.get_json(force=True)<br><br>            name = payload[&#39;name&#39;]<br>            email = payload[&#39;email&#39;]<br>            password = payload[&#39;password&#39;]<br><br>            db_conn = get_db_connection()<br>            db_conn.execute(<br>                &quot;INSERT INTO users (name, email, password) VALUES (?, ?, ?)&quot;,<br>                (name, email, password)<br>            )<br>            db_conn.commit()<br>            db_conn.close()<br><br>            return {<br>                &#39;success&#39;: True,<br>            }, 200<br><br>        except ValidationError as e:<br>            return {<br>                &#39;success&#39;: False,<br>                &#39;error&#39;: e.messages,<br>            }, 400<br><br>        except Exception as e:<br>            return {<br>                &#39;success&#39;: False,<br>                &#39;error&#39;: &quot;Something went wrong. Please try again&quot;<br>            }, 500</pre><p>If you notice we aren’t really doing any checks here for the incoming payload and implementing a rigorous check for each field again and again is not a good practice. Thankfully, we can make use of a popular and robust package called <a href="https://marshmallow.readthedocs.io/en/stable/">marshmallow</a> which does all the heavy lifting for us and gives us a simple API and functions to validate our incoming payload.</p><h4>Adding validation (marshmallow)</h4><p>Let’s start by installing marshmallow to our project.</p><pre>(flask-blog-api-venv) $ pip3 install marshmallow</pre><p>We can use marshmallow’s <a href="https://marshmallow.readthedocs.io/en/stable/quickstart.html#declaring-schemas">schema</a> to define the structure of our request payload and marshmallow would throw error if the payload does not match the structure of our schema.</p><p>Let’s now define the structure of our payload by creating a schema. Create a file at flask-blog-api/flask_blog_api/schemas/auth.py and put the following contents in it:</p><pre>### flask-blog-api/flask_blog_api/schemas/auth.py<br><br><br>from marshmallow import Schema, fields<br><br>class RegisterUserSchema(Schema):<br>    name = fields.Str(required=True)<br>    email = fields.Email(required=True)<br>    password = fields.Str(required=True)</pre><p>Before we create our RegisterRoute we need some util functions.</p><p>Install the secrets package:</p><pre>(flask-blog-api-venv) $ pip3 install secrets becrypt</pre><p>Create a new file called utils.py with the following functions:</p><pre>### flask-blog-api/flask_blog_api/helpers/utils.py<br><br><br>import secrets<br><br>def get_token_from_request(req):<br>    auth_token_header = req.headers.get(&#39;authorization&#39;)<br>    if auth_token_header:<br>        return auth_token_header.replace(&#39;Bearer &#39;, &#39;&#39;)<br>    return None<br><br>def generate_auth_token():<br>    # Generate a 32-byte random token<br>    token = secrets.token_bytes(32)<br>    # Convert the token to a hexadecimal string<br>    return  token.hex()</pre><p>Now, let’s update RegisterRoute and use the schema for validating the request payload.</p><pre>### flask-blog-api/flask_blog_api/resources/auth_resources.py<br><br><br># ...<br><br>from helpers.utils import (generate_auth_token, get_hashed_password)<br>from schemas.auth import RegisterUserSchema<br><br>register_user_schema = RegisterUserSchema()<br><br>class RegisterRoute(Resource):<br>    def post(self):<br>        try:<br>            payload = request.get_json(force=True)<br><br>            data = register_user_schema.load(payload)<br><br>            db_conn = get_db_connection()<br>            user = db_conn.execute(<br>                &quot;SELECT * FROM users WHERE email = ?&quot;,<br>                (data[&#39;email&#39;],)<br>            ).fetchone()<br><br>            if user:<br>                return {<br>                    &#39;success&#39;: False,<br>                    &#39;error&#39;: &#39;User with that email already exists&#39;<br>                }, 400<br><br>            name = data[&#39;name&#39;]<br>            email = data[&#39;email&#39;]<br>            password = get_hashed_password(data[&#39;password&#39;])<br>            token = generate_auth_token()<br> <br>            db_conn.execute(<br>                &quot;INSERT INTO users (name, email, password, token) VALUES (?, ?, ?, ?)&quot;,<br>                (name, email, password, token)<br>            )<br><br>            db_conn.commit()<br>            db_conn.close()<br><br># ...</pre><p>Create the LoginRoute inside the same resources/auth_resources.py file and its associated schema in schemas/auth.py.</p><pre>### flask-blog-api/flask_blog_api/schemas/auth.py<br><br><br># ...previous code<br><br>class LoginSchema(Schema):<br>    email = fields.Email(required=True)<br>    password = fields.Str(required=True)<br>    <br>class UserSchema(Schema):<br>    name = fields.Str()<br>    email = fields.Email()<br>    created_on = fields.DateTime()<br><br>class LoggedInUserSchema(UserSchema): <br>    token = fields.Str()<br>    password = fields.Str()</pre><p>Install the becrypt package:</p><pre>(flask-blog-api-venv) $ pip3 install becrypt</pre><p>Create a new file called utils.py with the following functions:</p><pre>### flask-blog-api/flask_blog_api/helpers/utils.py<br><br><br># ...<br>import bcrypt<br><br># Generate a salt for the password<br>salt = bcrypt.gensalt()<br><br># ...<br><br>def get_hashed_password(password):<br>    # Encrypt a password using the salt<br>    return bcrypt.hashpw(password.encode(&#39;utf-8&#39;), salt)<br><br>def password_matches(password, hashed_password):<br>    return bcrypt.checkpw(password.encode(&#39;utf-8&#39;), hashed_password.encode(&#39;utf-8&#39;))</pre><p>Finally create the LoginRoute:</p><pre>### flask-blog-api/flask_blog_api/resources/auth_resources.py<br><br><br># ...<br><br>from helpers.utils import (generate_auth_token, get_hashed_password,<br>                           password_matches)<br>from marshmallow import ValidationError<br>from schemas.auth import (LoggedInUserSchema, LoginSchema, RegisterUserSchema,<br>                          UserSchema)<br><br># ...<br><br>login_schema = LoginSchema()<br>user_schema = UserSchema()<br>logged_in_user_schema = LoggedInUserSchema()<br><br># ...<br><br>class LoginRoute(Resource):<br>    def post(self):<br>        try:<br>            payload = request.get_json(force=True)<br><br>            data = login_schema.load(payload)<br>            email = data[&#39;email&#39;]<br>            password = data[&#39;password&#39;]<br><br>            db_conn = get_db_connection()<br>            user = db_conn.execute(<br>                &quot;SELECT * FROM users WHERE email = ?&quot;,<br>                (email,)<br>            ).fetchone()<br>            db_conn.close()<br><br>            user_obj = logged_in_user_schema.dump(user)<br><br>            # validations<br>            if user is None:<br>                return {<br>                    &#39;success&#39;: False,<br>                    &#39;error&#39;: &#39;User does not exists&#39;<br>                }, 404<br><br>            if password_matches(password, user_obj[&#39;password&#39;]):<br>                return {<br>                    &#39;success&#39;: False,<br>                    &#39;error&#39;: &#39;Incorrect password&#39;<br>                }, 401<br><br>            return {<br>                &#39;success&#39;: True,<br>                &#39;data&#39;: user_obj,<br>            }, 200<br><br>        except ValidationError as e:<br>            return {<br>                &#39;success&#39;: False,<br>                &#39;error&#39;: e.messages,<br>            }, 400<br><br>        except Exception as e:<br>            return {<br>                &#39;success&#39;: False,<br>                &#39;error&#39;: &quot;Something went wrong. Please try again&quot;<br>            }, 500</pre><h4>Middlewares</h4><p>Before we jump into making other endpoints, we first need to add some layer of authentication for some requests. This can be done by implementing middlewares.</p><pre>### flask-blog-api/flask_blog_api/middlewares/authentication_middleware.py<br><br><br>import json<br><br>from helpers.utils import get_token_from_request<br>from werkzeug.wrappers import Request, Response<br><br>authenticated_request_paths = [<br>    &#39;/create&#39;,<br>]<br><br>unauthenticated_request_paths = [<br>    &#39;/&#39;<br>]<br><br>class AuthenticationMiddleware(object):<br>    def __init__(self, app):<br>        self.app = app<br><br>    def __call__(self, environ, resp):<br>        # not Flask request - from werkzeug.wrappers import Request<br>        request = Request(environ)<br>        request_path = request.path<br><br>        # By pass OPTIONS request from checking for authentication; fixed for website /questions<br>        # ref: https://cloud.google.com/functions/docs/writing/http#limitations<br>        if request.method != &#39;OPTIONS&#39; and \\<br>                request_path not in unauthenticated_request_paths and \\<br>                any(rp in request_path for rp in authenticated_request_paths):<br><br>            # token validation<br>            request_token = get_token_from_request(request)<br><br>            if not request_token:<br>                res = Response(<br>                    json.dumps({<br>                        &#39;success&#39;: False,<br>                        &#39;error&#39;: &#39;Unauthorized access&#39;<br>                    }),<br>                    status=401,<br>                    mimetype=&quot;application/json&quot;,<br>                )<br>                return res(environ, resp)<br><br>        return self.app(environ, resp)</pre><p>Update the app.py file to include our new middleware:</p><pre>### flask-blog-api/flask_blog_api/app.py<br><br><br># ...<br><br>from middlewares.authentication_middleware import AuthenticationMiddleware<br><br># ...<br><br>app.wsgi_app = AuthenticationMiddleware(app.wsgi_app)<br><br>if __name__ == &#39;__main__&#39;:<br>    app.run(debug=True, port=5001)</pre><h4>Posts endpoints</h4><p>It’s now time to complete our application and make resources for remaining API endpoints.</p><pre>### flask-blog-api/flask_blog_api/schemas/blog.py<br><br><br>from marshmallow import Schema, fields<br><br>class CreateBlogPostSchema(Schema):<br>    title = fields.Str(required=True)<br>    content = fields.Str(required=True)<br>    is_published = fields.Bool()<br><br>class BlogPostSchema(Schema):<br>    title = fields.Str(required=True)<br>    content = fields.Str(required=True)<br>    is_published = fields.Bool()<br>    created_at = fields.Str()</pre><pre>### flask-blog-api/flask_blog_api/resources/blog_resources.py<br><br><br>from flask import request<br>from flask_restful import Resource<br>from helpers.database import get_db_connection<br>from marshmallow import ValidationError<br>from schemas.blog import BlogPostSchema, CreateBlogPostSchema<br><br><br>create_blog_post_schema = CreateBlogPostSchema()<br>blog_post_schema = BlogPostSchema()<br>all_blog_posts_schema = BlogPostSchema(many=True)<br><br>class CreateBlogPostRoute(Resource):<br>    def post(self):<br>        try:<br>            payload = request.get_json(force=True)<br>            data = create_blog_post_schema.load(payload)<br><br>            title = data[&#39;title&#39;]<br>            content = data[&#39;content&#39;]<br>            is_published = data[&#39;is_published&#39;] if &#39;is_published&#39; in data else True<br><br>            db_conn = get_db_connection()<br>            cursor = db_conn.execute(<br>                &quot;INSERT INTO posts (title, content, is_published) VALUES (?, ?, ?)&quot;,<br>                (title, content, is_published)<br>            )<br>            db_conn.commit()<br><br>            new_post = db_conn.execute(<br>                &quot;SELECT * FROM posts WHERE id = ?&quot;,<br>                (cursor.lastrowid,)<br>            ).fetchone()<br>            db_conn.close()<br><br>            result = blog_post_schema.dump(new_post)<br><br>            return {<br>                &#39;success&#39;: True,<br>                &#39;data&#39;: result,<br>            }, 200<br><br>        except ValidationError as e:<br>            return {<br>                &#39;success&#39;: False,<br>                &#39;error&#39;: e.messages,<br>            }, 400<br><br>        except Exception as e:<br>            return {<br>                &#39;success&#39;: False,<br>                &#39;error&#39;: &quot;Something went wrong. Please try again&quot;<br>            }, 500<br><br>class BlogPostRoute(Resource):<br>    def get(self, post_id):<br>        try:<br>            db_conn = get_db_connection()<br>            post = db_conn.execute(<br>                &quot;SELECT * FROM posts WHERE id = ?&quot;,<br>                (post_id,)<br>            ).fetchone()<br>            db_conn.close()<br><br>            # validations<br>            if post is None:<br>                return {<br>                    &#39;success&#39;: False,<br>                    &#39;error&#39;: &#39;Post does not exists&#39;<br>                }, 404<br><br>            result = blog_post_schema.dump(post)<br><br>            return {<br>                &#39;success&#39;: True,<br>                &#39;data&#39;: result,<br>            }, 200<br><br>        except ValidationError as e:<br>            return {<br>                &#39;success&#39;: False,<br>                &#39;error&#39;: e.messages,<br>            }, 400<br><br>        except Exception as e:<br>            return {<br>                &#39;success&#39;: False,<br>                &#39;error&#39;: &quot;Something went wrong. Please try again&quot;<br>            }, 500<br><br>class AllBlogPostsRoute(Resource):<br>    def get(self):<br>        try:<br>            db_conn = get_db_connection()<br>            posts = db_conn.execute(<br>                &quot;SELECT * FROM posts \\<br>                ORDER BY created_at DESC \\<br>                LIMIT 10&quot;<br>            ).fetchall()<br>            db_conn.close()<br><br>            result = all_blog_posts_schema.dump(posts)<br><br>            return {<br>                &#39;success&#39;: True,<br>                &#39;data&#39;: result,<br>            }, 200<br><br>        except ValidationError as e:<br>            return {<br>                &#39;success&#39;: False,<br>                &#39;error&#39;: e.messages,<br>            }, 400<br><br>        except Exception as e:<br>            return {<br>                &#39;success&#39;: False,<br>                &#39;error&#39;: &quot;Something went wrong. Please try again&quot;<br>            }, 500</pre><p>This concludes our application.</p><h4>Miscellaneous</h4><p>To save all the packages we have installed in a file, we can use pip freeze and save it in requirements.txt file:</p><pre>(flask-blog-api-venv) $ cd flask_blog_api<br>(flask-blog-api-venv) $ pip3 freeze &gt;&gt; requirements.txt</pre><p>Also make sure to now put requirements.txt file in gitignore.</p><p>This concludes our application. You can find the complete repository on github <a href="https://github.com/DevangMstryls/flask-blog-api.git">here</a>.</p><blockquote><em>Please report issues if you find any. If you liked the post, don’t forget to leave a few</em>👏 <em>claps and share :)</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f838cf690fe7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>