{"id":3801,"date":"2024-12-10T12:29:19","date_gmt":"2024-12-10T12:29:19","guid":{"rendered":"https:\/\/www.talentelgia.com\/blog\/?p=3801"},"modified":"2024-12-26T06:52:36","modified_gmt":"2024-12-26T06:52:36","slug":"how-to-build-a-restful-api-in-python-using-flask-and-postgresql","status":"publish","type":"post","link":"https:\/\/www.talentelgia.com\/blog\/how-to-build-a-restful-api-in-python-using-flask-and-postgresql\/","title":{"rendered":"How to Build a RESTful API in Python Using Flask and PostgreSQL"},"content":{"rendered":"<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_73 counter-hierarchy ez-toc-counter ez-toc-grey ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<span class=\"ez-toc-title-toggle\"><a href=\"#\" class=\"ez-toc-pull-right ez-toc-btn ez-toc-btn-xs ez-toc-btn-default ez-toc-toggle\" aria-label=\"Toggle Table of Content\"><span class=\"ez-toc-js-icon-con\"><span class=\"\"><span class=\"eztoc-hide\" style=\"display:none;\">Toggle<\/span><span class=\"ez-toc-icon-toggle-span\"><svg style=\"fill: #999;color:#999\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewBox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #999;color:#999\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewBox=\"0 0 24 24\" version=\"1.2\" baseProfile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/span><\/span><\/a><\/span><\/div>\n<nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/www.talentelgia.com\/blog\/how-to-build-a-restful-api-in-python-using-flask-and-postgresql\/#Step_By_Step_Guide_To_Build_an_API\" title=\"Step By Step Guide To Build an API\">Step By Step Guide To Build an API<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/www.talentelgia.com\/blog\/how-to-build-a-restful-api-in-python-using-flask-and-postgresql\/#Step_1_Project_Setup\" title=\"Step 1: Project Setup\">Step 1: Project Setup<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/www.talentelgia.com\/blog\/how-to-build-a-restful-api-in-python-using-flask-and-postgresql\/#Step_2_Database_Configuration\" title=\"Step 2: Database Configuration\">Step 2: Database Configuration<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/www.talentelgia.com\/blog\/how-to-build-a-restful-api-in-python-using-flask-and-postgresql\/#Step_3_Setting_Up_the_Database_Models\" title=\"Step 3: Setting Up the Database Models\">Step 3: Setting Up the Database Models<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/www.talentelgia.com\/blog\/how-to-build-a-restful-api-in-python-using-flask-and-postgresql\/#Step_4_Controllers_Layer\" title=\"Step 4: Controllers Layer\">Step 4: Controllers Layer<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/www.talentelgia.com\/blog\/how-to-build-a-restful-api-in-python-using-flask-and-postgresql\/#Step_5_Service_Layer\" title=\"Step 5: Service Layer\">Step 5: Service Layer<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/www.talentelgia.com\/blog\/how-to-build-a-restful-api-in-python-using-flask-and-postgresql\/#Step_6_Repository_Layer\" title=\"Step 6: Repository Layer\">Step 6: Repository Layer<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-8\" href=\"https:\/\/www.talentelgia.com\/blog\/how-to-build-a-restful-api-in-python-using-flask-and-postgresql\/#Step_7_Serializers_layer\" title=\"Step 7: Serializers layer\">Step 7: Serializers layer<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-9\" href=\"https:\/\/www.talentelgia.com\/blog\/how-to-build-a-restful-api-in-python-using-flask-and-postgresql\/#Step_8_Utils_layer\" title=\"Step 8: Utils layer\">Step 8: Utils layer<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-10\" href=\"https:\/\/www.talentelgia.com\/blog\/how-to-build-a-restful-api-in-python-using-flask-and-postgresql\/#Step_9_Entry_point\" title=\"Step 9: Entry point\">Step 9: Entry point<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-11\" href=\"https:\/\/www.talentelgia.com\/blog\/how-to-build-a-restful-api-in-python-using-flask-and-postgresql\/#Step_10_Running_our_application\" title=\"Step 10: Running our application\">Step 10: Running our application<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-12\" href=\"https:\/\/www.talentelgia.com\/blog\/how-to-build-a-restful-api-in-python-using-flask-and-postgresql\/#Conclusion\" title=\"Conclusion\">Conclusion<\/a><\/li><\/ul><\/nav><\/div>\n\n<p>In this tutorial, we will walk through creating a simple yet organized Python API using Flask and PostgreSQL. We will use SQLAlchemy to interact with the database and organize our code into separate modules for maintainability. The goal is to create a clean, scalable structure for building and expanding the application as needed.<\/p>\n\n\n\n<p>In this tutorial, we are going to use the below directory structure:<\/p>\n\n\n\n<pre class=\"wp-block-code has-white-color has-black-background-color has-text-color has-background has-link-color wp-elements-d358a61d9940eb31a68bbe0ded301d74\"><code>\u251c\u2500\u2500 app.<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-cyan-blue-color\">py<\/mark>\n\u251c\u2500\u2500 configs\n\u2502   \u251c\u2500\u2500 db_config.<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-cyan-blue-color\">py<\/mark>\n\u251c\u2500\u2500 controllers\n\u2502   \u2514\u2500\u2500 user_controller.<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-cyan-blue-color\">py<\/mark>\n\u251c\u2500\u2500 models\n\u2502   \u251c\u2500\u2500 base_model.<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-cyan-blue-color\">py<\/mark>\n\u2502   \u2514\u2500\u2500 user_model.<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-cyan-blue-color\">py<\/mark>\n\u251c\u2500\u2500 repository\n\u2502   \u2514\u2500\u2500 user_repository.<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-cyan-blue-color\">py<\/mark>\n\u251c\u2500\u2500 requirements.<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-cyan-blue-color\">txt<\/mark>\n\u251c\u2500\u2500 serializers\n\u2502   \u2514\u2500\u2500 user_serializer.<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-cyan-blue-color\">py<\/mark>\n\u251c\u2500\u2500 services\n\u2502   \u2514\u2500\u2500 user_service.<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-cyan-blue-color\">py<\/mark>\n\u2514\u2500\u2500 utils\n   \u2514\u2500\u2500 helper_functions.<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-cyan-blue-color\">py<\/mark><\/code><\/pre>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>app.py<\/strong>: The main entry point for the application.<\/li>\n\n\n\n<li><strong>models<\/strong>: Contains database models.<\/li>\n\n\n\n<li><strong>controllers<\/strong>: Handles HTTP requests and responses.<\/li>\n\n\n\n<li><strong>repository<\/strong>: Responsible for database operations.<\/li>\n\n\n\n<li><strong>services<\/strong>: Contains business logic.<\/li>\n\n\n\n<li><strong>serializers<\/strong>: Validates and serializes input data.<\/li>\n\n\n\n<li><strong>utils<\/strong>: Utility functions, such as password handling<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Step_By_Step_Guide_To_Build_an_API\"><\/span><strong>Step By Step Guide To Build an API<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Step_1_Project_Setup\"><\/span><strong>Step 1: Project Setup<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>We begin by setting up a Python project and installing the necessary packages. To install Flask, SQLAlchemy, and psycopg2 (the PostgreSQL adapter for Python), open the terminal and run the following command<\/p>\n\n\n\n<pre class=\"wp-block-code has-white-color has-black-background-color has-text-color has-background has-link-color wp-elements-d5b09ac2e396001cb1b1fe7a6aac02f5\"><code>pip <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">install<\/mark> flask sqlalchemy psycopg2<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Step_2_Database_Configuration\"><\/span><strong>Step 2: Database Configuration<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>Create a file in the configs directory and add the code snippet below &#8211;<\/p>\n\n\n\n<pre class=\"wp-block-code has-white-color has-black-background-color has-text-color has-background has-link-color wp-elements-07a07425fab0c6b2a0cb17fc8f0574ae\"><code><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">import<\/mark> os\n<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">class<\/mark> <mark style=\"background-color:rgba(0, 0, 0, 0);color:#f1c651\" class=\"has-inline-color\">Config<\/mark>:\n   <mark style=\"background-color:rgba(0, 0, 0, 0);color:#f1c651\" class=\"has-inline-color\">SQLALCHEMY_DATABASE_URI = os.environ.get<\/mark>(<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-green-cyan-color\">'DATABASE_URL<\/mark>', <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-green-cyan-color\">'postgresql+psycopg2:\/\/username:password@localhost\/my_api_db'<\/mark>)\n   SQLALCHEMY_TRACK_MODIFICATIONS = False<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Step_3_Setting_Up_the_Database_Models\"><\/span><strong>Step 3: Setting Up the Database Models<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>Now, let&#8217;s define our database models. These models typically represent the structure of our database tables. Using an ORM (Object-Relational Mapping) makes managing database queries straightforward and secure, as it automatically helps prevent SQL injection. Create a file in the &#8220;models&#8221; directory and add the following code snippet:<\/p>\n\n\n\n<pre class=\"wp-block-code has-white-color has-black-background-color has-text-color has-background has-link-color wp-elements-57b763f211e3816a489f570b56874746\"><code><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">from<\/mark> sqlalchemy.ext.declarative import declarative_base\n<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">from<\/mark> sqlalchemy.orm import sessionmaker\n<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">from<\/mark> sqlalchemy import create_engine\n<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">from<\/mark> configs.db_config import DATABASE_URI\nBase = declarative_base()\nengine = create_engine(DATABASE_URI)\nSessionLocal = sessionmaker(<mark style=\"background-color:rgba(0, 0, 0, 0);color:#f1c651\" class=\"has-inline-color\">autocommit<\/mark>=<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">False<\/mark>, <mark style=\"background-color:rgba(0, 0, 0, 0);color:#f1c651\" class=\"has-inline-color\">autoflush<\/mark>=<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-white-color\">False<\/mark>, <mark style=\"background-color:rgba(0, 0, 0, 0);color:#f1c651\" class=\"has-inline-color\">bind<\/mark>=<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">engine<\/mark>)<\/code><\/pre>\n\n\n\n<p>Now let&#8217;s set up our user model. Create another file in the model&#8217;s directory and add the code snippet below &#8211;<\/p>\n\n\n\n<pre class=\"wp-block-code has-white-color has-black-background-color has-text-color has-background has-link-color wp-elements-6e3c87af03a0a612bb6568b43e48c6f0\"><code><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">from<\/mark> sqlalchemy import Column, Integer, String\n<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">from<\/mark> .base_model import Base\nclass User(Base):\n   __tablename__ = <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-green-cyan-color\">\"users\"<\/mark>\n   id = Column(Integer, <mark style=\"background-color:rgba(0, 0, 0, 0);color:#f1c651\" class=\"has-inline-color\">primary_key<\/mark>=<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">True<\/mark>, <mark style=\"background-color:rgba(0, 0, 0, 0);color:#f1c651\" class=\"has-inline-color\">index<\/mark>=<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">True<\/mark>)\n   first_name = Column(String, <mark style=\"background-color:rgba(0, 0, 0, 0);color:#f1c651\" class=\"has-inline-color\">nullable<\/mark>=<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">False<\/mark>)\n   last_name = Column(String, <mark style=\"background-color:rgba(0, 0, 0, 0);color:#f1c651\" class=\"has-inline-color\">nullable<\/mark>=<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">False<\/mark>)\n   email = Column(String, <mark style=\"background-color:rgba(0, 0, 0, 0);color:#f1c651\" class=\"has-inline-color\">unique<\/mark>=True, <mark style=\"background-color:rgba(0, 0, 0, 0);color:#f1c651\" class=\"has-inline-color\">nullable<\/mark>=<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">False<\/mark>)\n   mobile_number = Column(String, <mark style=\"background-color:rgba(0, 0, 0, 0);color:#f1c651\" class=\"has-inline-color\">unique<\/mark>=<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">True<\/mark>, <mark style=\"background-color:rgba(0, 0, 0, 0);color:#f1c651\" class=\"has-inline-color\">nullable<\/mark>=<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">False<\/mark>)\n   password = Column(String, <mark style=\"background-color:rgba(0, 0, 0, 0);color:#f1c651\" class=\"has-inline-color\">nullable<\/mark>=<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">False<\/mark>)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Step_4_Controllers_Layer\"><\/span><strong>Step 4: Controllers Layer<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>Controllers basically control our data flow throughout the request\/response cycle. We set all our routes here so let&#8217;s create a file in the controller&#8217;s directory and add the code snippet &#8211;<\/p>\n\n\n\n<pre class=\"wp-block-code has-white-color has-black-background-color has-text-color has-background has-link-color wp-elements-73382a89cc83b833019397c6c7be6cc9\"><code><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">from<\/mark> flask <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">import<\/mark> Blueprint, request, jsonify\n<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">from<\/mark> sqlalchemy.orm <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">import<\/mark> Session\n<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">from<\/mark> models.base_model <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">import<\/mark> SessionLocal\n<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">from<\/mark> services.user_service <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">import<\/mark> (\n   add_user_service, list_users_service, get_user_service,\n   update_user_service, delete_user_service\n)\n<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">from<\/mark> serializers.user_serializer <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">import<\/mark> UserCreate, UserUpdate, UserResponse\n<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">from<\/mark> pydantic <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">import<\/mark> ValidationError\nuser_bp = Blueprint(\"user\", __name__)\n<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">def<\/mark> <mark style=\"background-color:rgba(0, 0, 0, 0);color:#f1c651\" class=\"has-inline-color\">get_db()<\/mark>:\n   db = SessionLocal()\n   <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">try<\/mark>:\n       <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">yield<\/mark> db\n   <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">finally<\/mark>:\n       db.close()\n<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-red-color\">@user_bp.route(\"\/\", methods=&#91;\"POST\"])<\/mark>\n<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">def<\/mark> <mark style=\"background-color:rgba(0, 0, 0, 0);color:#f1c651\" class=\"has-inline-color\">create_user<\/mark><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-white-color\">()<\/mark>:\n   db = next(get_db())\n   <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">try<\/mark>:\n       data = request.get_json()\n       user_data = UserCreate(**data)\n       user = add_user_service(db, user_data)\n       <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">return<\/mark> jsonify(UserResponse.from_orm(user).dict()), 201\n   <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">except<\/mark> ValidationError <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">as<\/mark> e:\n       <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">return<\/mark> jsonify({\"error\": e.errors()}), 400\n@user_bp.route(\"\/\", methods=&#91;\"GET\"])\n<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">def<\/mark> <mark style=\"background-color:rgba(0, 0, 0, 0);color:#f1c651\" class=\"has-inline-color\">list_users<\/mark>():\n   db = next(get_db())\n   users = list_users_service(db)\n   <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">return<\/mark> jsonify(&#91;UserResponse.from_orm(user).dict() <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">for<\/mark> user <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">in<\/mark> users]), 200\n<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-red-color\">@user_bp.route(\"\/&lt;int:user_id&gt;\", methods=&#91;\"GET\"])<\/mark>\n<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">def<\/mark> <mark style=\"background-color:rgba(0, 0, 0, 0);color:#f1c651\" class=\"has-inline-color\">get_user<\/mark>(user_id):\n   db = next(get_db())\n   user = get_user_service(db, user_id)\n  <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\"> if not <\/mark><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-white-color\">user<\/mark>:\n       <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">return<\/mark> jsonify({\"error\": \"User not found\"}), <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-red-color\">404<\/mark>\n   <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">return<\/mark> jsonify(UserResponse.from_orm(user).dict()), <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-red-color\">200<\/mark>\n<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-red-color\">@user_bp.route(\"\/&lt;int:user_id&gt;\", methods=&#91;\"PATCH\"])<\/mark>\n<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">def<\/mark> <mark style=\"background-color:rgba(0, 0, 0, 0);color:#f1c651\" class=\"has-inline-color\">update_user<\/mark>(user_id):\n   db = next(get_db())\n   <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">try<\/mark>:\n       data = request.get_json()\n       updates = UserUpdate(**data)\n       user = update_user_service(db, user_id, updates)\n      <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\"> if not <\/mark><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-white-color\">user<\/mark>:\n           <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">return<\/mark> jsonify({\"error\": \"User not found\"}), <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-red-color\">404<\/mark>\n       <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">return<\/mark> jsonify(UserResponse.from_orm(user).dict()), <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-red-color\">200<\/mark>\n   except ValidationError <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">as<\/mark> e:\n       <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">return<\/mark> jsonify({\"error\": e.errors()}), <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-red-color\">400<\/mark>\n<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-red-color\">@user_bp.route(\"\/&lt;int:user_id&gt;\", methods=&#91;\"DELETE\"])<\/mark>\ndef <mark style=\"background-color:rgba(0, 0, 0, 0);color:#f1c651\" class=\"has-inline-color\">delete_user<\/mark>(user_id):\n   db = next(get_db())\n   user = delete_user_service(db, user_id)\n<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">   if not <\/mark><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-white-color\">user:<\/mark>\n       <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">return<\/mark> jsonify({\"error\": \"User not found\"}), <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-red-color\">404<\/mark>\n   <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">return<\/mark> jsonify({\"message\": \"User deleted\"}), <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-red-color\">200<\/mark><\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Step_5_Service_Layer\"><\/span><strong>Step 5: Service Layer<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>This layer contains our core logic\u2014all kinds of things like checking duplicity and hashing of passwords, etc. We usually do that in the service layer. Create a file in the services directory and add the below lines &#8211;<\/p>\n\n\n\n<pre class=\"wp-block-code has-white-color has-black-background-color has-text-color has-background has-link-color wp-elements-334021a0cf0cd45c4f3ca5614351be1b\"><code><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">from<\/mark> repository.user_repository <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">import<\/mark> (\n   create_user, get_all_users, get_user_by_id, update_user, delete_user\n)\n<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">from<\/mark> utils.helper_functions <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">import<\/mark> hash_password\n<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">from<\/mark> sqlalchemy.orm <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">import<\/mark> Session\n<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">from<\/mark> serializers.user_serializer <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">import<\/mark> UserCreate, UserUpdate\n<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">def<\/mark> <mark style=\"background-color:rgba(0, 0, 0, 0);color:#f1c651\" class=\"has-inline-color\">add_user_service<\/mark>(db: Session, user_data: UserCreate):\n   user_data.password = hash_password(user_data.password)\n   return create_user(db, user_data.dict())\n<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">def<\/mark> <mark style=\"background-color:rgba(0, 0, 0, 0);color:#f1c651\" class=\"has-inline-color\">list_users_service<\/mark>(db: Session):\n   return get_all_users(db)\n<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">def<\/mark> <mark style=\"background-color:rgba(0, 0, 0, 0);color:#f1c651\" class=\"has-inline-color\">get_user_service<\/mark>(db: Session, user_id: int):\n   return get_user_by_id(db, user_id)\n<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">def<\/mark> <mark style=\"background-color:rgba(0, 0, 0, 0);color:#f1c651\" class=\"has-inline-color\">update_user_service<\/mark>(db: Session, user_id: int, updates: UserUpdate):\n   if updates.password:\n       updates.password = hash_password(updates.password)\n   return update_user(db, user_id, updates.dict(exclude_unset=True))\n<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">def<\/mark> <mark style=\"background-color:rgba(0, 0, 0, 0);color:#f1c651\" class=\"has-inline-color\">delete_user_service<\/mark>(db: Session, user_id: int):\n   return delete_user(db, user_id)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Step_6_Repository_Layer\"><\/span><strong>Step 6: Repository Layer<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>This layer communicates with the Database. Create a file in the repository directory and add the code snippet below &#8211;<\/p>\n\n\n\n<pre class=\"wp-block-code has-white-color has-black-background-color has-text-color has-background has-link-color wp-elements-da23c2d344311571568e911083dcdda1\"><code><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">from<\/mark> sqlalchemy.orm import Session\n<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">from<\/mark> models.user_model import <mark style=\"background-color:rgba(0, 0, 0, 0);color:#f1c651\" class=\"has-inline-color\">User<\/mark>\n<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">def<\/mark> <mark style=\"background-color:rgba(0, 0, 0, 0);color:#f1c651\" class=\"has-inline-color\">create_user<\/mark>(db: Session, user_data: dict):\n   <mark style=\"background-color:rgba(0, 0, 0, 0);color:#f1c651\" class=\"has-inline-color\">user<\/mark> = User(**user_data)\n   db.<mark style=\"background-color:rgba(0, 0, 0, 0);color:#f1c651\" class=\"has-inline-color\">add<\/mark>(user)\n   db.commit()\n   db.refresh(user)\n<mark style=\"background-color:rgba(0, 0, 0, 0);color:#f1c651\" class=\"has-inline-color\">   return user<\/mark>\n<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">def<\/mark> <mark style=\"background-color:rgba(0, 0, 0, 0);color:#f1c651\" class=\"has-inline-color\">get_all_users<\/mark>(db: Session):\n   return db.query(User).all()\n<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">def<\/mark> <mark style=\"background-color:rgba(0, 0, 0, 0);color:#f1c651\" class=\"has-inline-color\">get_user_by_id<\/mark>(db: Session, user_id: int):\n   return db.query(User).filter(User.id == user_id).first()\n<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">def<\/mark> update_user(db: Session, user_id: int, updates: dict):\n   <mark style=\"background-color:rgba(0, 0, 0, 0);color:#f1c651\" class=\"has-inline-color\">user<\/mark> = db.query(User).filter(User.id == user_id).first()\n  <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\"> if user<\/mark>:\n       for key, value in updates.items():\n           setattr(user, key, value)\n       db.commit()\n       db.refresh(user)\n<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">   return user<\/mark>\n<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">def<\/mark> <mark style=\"background-color:rgba(0, 0, 0, 0);color:#f1c651\" class=\"has-inline-color\">delete_user<\/mark>(db: Session, user_id: int):\n   user = db.query(User).filter(User.id == user_id).first()\n  <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\"> if user<\/mark>:\n       db.delete(user)\n       db.commit()\n<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">   return user<\/mark><\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Step_7_Serializers_layer\"><\/span><strong>Step 7: Serializers layer<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>Serializers are a way to serialize our output. We can control what should be the contents of the output because we don\u2019t want to send the hashed password in the API response. Create a file in the serializers directory and add the code snippet &#8211;<\/p>\n\n\n\n<pre class=\"wp-block-code has-white-color has-black-background-color has-text-color has-background has-link-color wp-elements-579ad47cc2149ac42b8833bb0d3dc9e5\"><code><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">from<\/mark> pydantic <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">import<\/mark> BaseModel, Field, EmailStr\n<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">class<\/mark> <mark style=\"background-color:rgba(0, 0, 0, 0);color:#f1c651\" class=\"has-inline-color\">UserBase<\/mark>(BaseModel):\n   first_name: str = Field(..., min_length=<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-red-color\">1<\/mark>, max_length=<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-red-color\">50<\/mark>)\n   last_name: str = Field(..., min_length=<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-red-color\">1<\/mark>, max_length=<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-red-color\">50<\/mark>)\n   email: str = Field(..., pattern=<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-green-cyan-color\">r\"^&#91;^@]+@&#91;^@]+\\.&#91;^@]+$\"<\/mark>)\n   mobile_number: str = Field(..., pattern=<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-green-cyan-color\">r\"^\\+?\\d{10,15}$\"<\/mark>)\n<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">class<\/mark> <mark style=\"background-color:rgba(0, 0, 0, 0);color:#f1c651\" class=\"has-inline-color\">UserCreate<\/mark>(UserBase):\n   password: str = Field(..., min_length=6)\n<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">class<\/mark> <mark style=\"background-color:rgba(0, 0, 0, 0);color:#f1c651\" class=\"has-inline-color\">UserUpdate<\/mark>(BaseModel):\n   first_name: str\n   last_name: str\n   email: EmailStr\n   mobile_number: str\n   password: str\n<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">class<\/mark> <mark style=\"background-color:rgba(0, 0, 0, 0);color:#f1c651\" class=\"has-inline-color\">UserResponse<\/mark>(UserBase):\n   id: int\n   <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">class<\/mark> <mark style=\"background-color:rgba(0, 0, 0, 0);color:#f1c651\" class=\"has-inline-color\">Config<\/mark>:\n       from_attributes = True<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Step_8_Utils_layer\"><\/span><strong>Step 8: Utils layer<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>The utils layer contains small utility functions that can be reused in our app. Create a file in the utils directory and add the code snippet &#8211;<\/p>\n\n\n\n<pre class=\"wp-block-code has-white-color has-black-background-color has-text-color has-background has-link-color wp-elements-f3c1f1926f68c46f56311b4303082718\"><code><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">from<\/mark> passlib.context <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">import<\/mark> CryptContext\npwd_context = CryptContext(schemes=&#91;<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-green-cyan-color\">\"bcrypt\"<\/mark>], deprecated=<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-green-cyan-color\">\"auto\"<\/mark>)\n<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">def<\/mark> <mark style=\"background-color:rgba(0, 0, 0, 0);color:#f1c651\" class=\"has-inline-color\">hash_password<\/mark>(password: str) -&gt; str:\n   <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">return<\/mark> pwd_context.hash(password)\n<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">def<\/mark> <mark style=\"background-color:rgba(0, 0, 0, 0);color:#f1c651\" class=\"has-inline-color\">verify_password<\/mark>(plain_password: str, hashed_password: str) -&gt; bool:\n   <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">return<\/mark> pwd_context.verify(plain_password, hashed_password)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Step_9_Entry_point\"><\/span><strong>Step 9: Entry point<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>Finally, create an entry point for our application. This file will serve as the main execution point and should be placed in the root directory. Add the following code to this file<\/p>\n\n\n\n<pre class=\"wp-block-code has-white-color has-black-background-color has-text-color has-background has-link-color wp-elements-925d5db531f054f17857e402d33fa8a9\"><code><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">from<\/mark> flask import Flask\n<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">from<\/mark> controllers.user_controller import user_bp\n<mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-luminous-vivid-orange-color\">from<\/mark> models.base_model import Base, engine\napp = Flask(__name__)\nBase.metadata.create_all(<mark style=\"background-color:rgba(0, 0, 0, 0);color:#f1c651\" class=\"has-inline-color\">bind<\/mark>=engine)\napp.register_blueprint(user_bp, <mark style=\"background-color:rgba(0, 0, 0, 0);color:#f1c651\" class=\"has-inline-color\">url_prefix=<\/mark><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-green-cyan-color\">\"\/users\"<\/mark>)\nif __name__ == <mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-green-cyan-color\">\"__main__\"<\/mark>:\n   app.<mark style=\"background-color:rgba(0, 0, 0, 0);color:#f1c651\" class=\"has-inline-color\">run(debug<\/mark>=True)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Step_10_Running_our_application\"><\/span><strong>Step 10: Running our application<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>Add your database URL in the config file open the terminal and use the command &#8211;<\/p>\n\n\n\n<p>python3 app.pyyour application with start to run on<a href=\"http:\/\/localhost:5000\"> http:\/\/localhost:5000<\/a> and you can access your routes as follows &#8211;<\/p>\n\n\n\n<pre class=\"wp-block-code has-white-color has-black-background-color has-text-color has-background has-link-color wp-elements-3aa57ea4f0f5fdc8f2157c55bdaf8930\"><code>POST \/<mark style=\"background-color:rgba(0, 0, 0, 0);color:#f1c651\" class=\"has-inline-color\">users<\/mark> - Create a <mark style=\"background-color:rgba(0, 0, 0, 0);color:#f1c651\" class=\"has-inline-color\">new user<\/mark>\n<mark style=\"background-color:rgba(0, 0, 0, 0);color:#f1c651\" class=\"has-inline-color\">GET \/users - Get all users<\/mark>\n<mark style=\"background-color:rgba(0, 0, 0, 0);color:#f1c651\" class=\"has-inline-color\">GET<\/mark> \/users\/&lt;user_id&gt; - <mark style=\"background-color:rgba(0, 0, 0, 0);color:#f1c651\" class=\"has-inline-color\">Get a user<\/mark> by ID\nPATCH \/users\/&lt;user_id&gt; - <mark style=\"background-color:rgba(0, 0, 0, 0);color:#f1c651\" class=\"has-inline-color\">Update a user<\/mark> by ID\nDELETE \/users\/&lt;user_id&gt; - <mark style=\"background-color:rgba(0, 0, 0, 0);color:#f1c651\" class=\"has-inline-color\">Delete a user<\/mark> by ID<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Conclusion\"><\/span><strong>Conclusion<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<pre class=\"wp-block-verse\">This Python API is built using Flask for handling web requests and SQLAlchemy for interacting with a PostgreSQL database. The application follows a modular structure, making it easy to maintain and expand as it grows. Here\u2019s a breakdown of the key components:<br><br><strong>app.py<\/strong>\u200a\u2014\u200aThis is the main entry point of the app. It sets up the Flask application, registers routes, and connects to the database.<br><strong>models<\/strong>\u200a\u2014\u200aThis file contains the database models, defining the structure of the tables and handling database operations.<br><strong>controllers<\/strong>\u200a\u2014\u200aThese are the functions that handle incoming HTTP requests, validate input, and send appropriate responses.<br><strong>repository<\/strong>\u200a\u2014\u200aThis layer is responsible for directly interacting with the database, performing CRUD (Create, Read, Update, Delete) operations.<br><strong>services<\/strong>\u200a\u2014\u200aHere is where the core business logic resides, including processing data and managing interactions with the repository layer.<br><strong>serializers<\/strong>\u200a\u2014\u200aThese ensure that input data is validated and serialized correctly before passing it to the services layer.<br><strong>utils<\/strong>\u200a\u2014\u200aThis folder contains utility functions for tasks like password hashing and verification.<br><br>This structure keeps the application organized, easy to extend, and clean. By separating concerns into specific files and directories, the application can grow and adapt without becoming unmanageable.<br><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>In this tutorial, we will walk through creating a simple yet organized Python API using Flask and PostgreSQL. We will use SQLAlchemy to interact with the database and organize our code into separate modules for maintainability. The goal is to create a clean, scalable structure for building and expanding the application as needed. In this [&hellip;]<\/p>\n","protected":false},"author":6,"featured_media":3892,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"inline_featured_image":false,"footnotes":""},"categories":[18],"tags":[],"class_list":["post-3801","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-web-development"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.1.1 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>How to Build a RESTful API in Python Using Flask and PostgreSQL<\/title>\n<meta name=\"description\" content=\"Learn how to build a RESTful API in Python using Flask and PostgreSQL. Step-by-step guide to creating, managing, and securing APIs with database integration.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.talentelgia.com\/blog\/how-to-build-a-restful-api-in-python-using-flask-and-postgresql\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"How to Build a RESTful API in Python Using Flask and PostgreSQL\" \/>\n<meta property=\"og:description\" content=\"Learn how to build a RESTful API in Python using Flask and PostgreSQL. Step-by-step guide to creating, managing, and securing APIs with database integration.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.talentelgia.com\/blog\/how-to-build-a-restful-api-in-python-using-flask-and-postgresql\/\" \/>\n<meta property=\"og:site_name\" content=\"Talentelgia\" \/>\n<meta property=\"article:published_time\" content=\"2024-12-10T12:29:19+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-12-26T06:52:36+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/www.talentelgia.com\/blog\/wp-content\/uploads\/2024\/12\/How-to-build-Restful-API-.webp\" \/>\n\t<meta property=\"og:image:width\" content=\"1920\" \/>\n\t<meta property=\"og:image:height\" content=\"1080\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/webp\" \/>\n<meta name=\"author\" content=\"Amandeep Singh\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Amandeep Singh\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"3 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/www.talentelgia.com\/blog\/how-to-build-a-restful-api-in-python-using-flask-and-postgresql\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/www.talentelgia.com\/blog\/how-to-build-a-restful-api-in-python-using-flask-and-postgresql\/\"},\"author\":{\"name\":\"Amandeep Singh\",\"@id\":\"https:\/\/www.talentelgia.com\/blog\/#\/schema\/person\/44b9de9c8d4826795325996e579d67e8\"},\"headline\":\"How to Build a RESTful API in Python Using Flask and PostgreSQL\",\"datePublished\":\"2024-12-10T12:29:19+00:00\",\"dateModified\":\"2024-12-26T06:52:36+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/www.talentelgia.com\/blog\/how-to-build-a-restful-api-in-python-using-flask-and-postgresql\/\"},\"wordCount\":508,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/www.talentelgia.com\/blog\/#organization\"},\"image\":{\"@id\":\"https:\/\/www.talentelgia.com\/blog\/how-to-build-a-restful-api-in-python-using-flask-and-postgresql\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/www.talentelgia.com\/blog\/wp-content\/uploads\/2024\/12\/How-to-build-Restful-API-.webp\",\"articleSection\":[\"Web Development\"],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/www.talentelgia.com\/blog\/how-to-build-a-restful-api-in-python-using-flask-and-postgresql\/\",\"url\":\"https:\/\/www.talentelgia.com\/blog\/how-to-build-a-restful-api-in-python-using-flask-and-postgresql\/\",\"name\":\"How to Build a RESTful API in Python Using Flask and PostgreSQL\",\"isPartOf\":{\"@id\":\"https:\/\/www.talentelgia.com\/blog\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/www.talentelgia.com\/blog\/how-to-build-a-restful-api-in-python-using-flask-and-postgresql\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/www.talentelgia.com\/blog\/how-to-build-a-restful-api-in-python-using-flask-and-postgresql\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/www.talentelgia.com\/blog\/wp-content\/uploads\/2024\/12\/How-to-build-Restful-API-.webp\",\"datePublished\":\"2024-12-10T12:29:19+00:00\",\"dateModified\":\"2024-12-26T06:52:36+00:00\",\"description\":\"Learn how to build a RESTful API in Python using Flask and PostgreSQL. Step-by-step guide to creating, managing, and securing APIs with database integration.\",\"breadcrumb\":{\"@id\":\"https:\/\/www.talentelgia.com\/blog\/how-to-build-a-restful-api-in-python-using-flask-and-postgresql\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/www.talentelgia.com\/blog\/how-to-build-a-restful-api-in-python-using-flask-and-postgresql\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.talentelgia.com\/blog\/how-to-build-a-restful-api-in-python-using-flask-and-postgresql\/#primaryimage\",\"url\":\"https:\/\/www.talentelgia.com\/blog\/wp-content\/uploads\/2024\/12\/How-to-build-Restful-API-.webp\",\"contentUrl\":\"https:\/\/www.talentelgia.com\/blog\/wp-content\/uploads\/2024\/12\/How-to-build-Restful-API-.webp\",\"width\":1920,\"height\":1080,\"caption\":\"Build a RESTful API in Python Using Flask and PostgreSQL\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/www.talentelgia.com\/blog\/how-to-build-a-restful-api-in-python-using-flask-and-postgresql\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/www.talentelgia.com\/blog\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"How to Build a RESTful API in Python Using Flask and PostgreSQL\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/www.talentelgia.com\/blog\/#website\",\"url\":\"https:\/\/www.talentelgia.com\/blog\/\",\"name\":\"Talentelgia\",\"description\":\"Latest Web &amp; Mobile Technologies, AI\/ML, and Blockchain Blogs\",\"publisher\":{\"@id\":\"https:\/\/www.talentelgia.com\/blog\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/www.talentelgia.com\/blog\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/www.talentelgia.com\/blog\/#organization\",\"name\":\"Talentelgia\",\"url\":\"https:\/\/www.talentelgia.com\/blog\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.talentelgia.com\/blog\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/www.talentelgia.com\/blog\/wp-content\/uploads\/2024\/01\/talentelgia-logo.svg\",\"contentUrl\":\"https:\/\/www.talentelgia.com\/blog\/wp-content\/uploads\/2024\/01\/talentelgia-logo.svg\",\"width\":159,\"height\":53,\"caption\":\"Talentelgia\"},\"image\":{\"@id\":\"https:\/\/www.talentelgia.com\/blog\/#\/schema\/logo\/image\/\"}},{\"@type\":\"Person\",\"@id\":\"https:\/\/www.talentelgia.com\/blog\/#\/schema\/person\/44b9de9c8d4826795325996e579d67e8\",\"name\":\"Amandeep Singh\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/www.talentelgia.com\/blog\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/www.talentelgia.com\/blog\/wp-content\/uploads\/2024\/11\/7EB3EE9B-4D5A-4F47-AB90-55A574FF9FE6-150x150.webp\",\"contentUrl\":\"https:\/\/www.talentelgia.com\/blog\/wp-content\/uploads\/2024\/11\/7EB3EE9B-4D5A-4F47-AB90-55A574FF9FE6-150x150.webp\",\"caption\":\"Amandeep Singh\"},\"description\":\"Amandeep is a dedicated tech enthusiast with a passion for simplifying complex concepts. With a keen eye for emerging technologies and a knack for sharing knowledge, he breaks down intricate tech topics into easy-to-understand explanations with his blogs. With a keen interest in emerging technologies, Amandeep strives to make technology accessible to everyone.\",\"sameAs\":[\"https:\/\/www.linkedin.com\/company\/talentelgia-technologies\/\"],\"url\":\"https:\/\/www.talentelgia.com\/blog\/author\/amandeep-singh\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"How to Build a RESTful API in Python Using Flask and PostgreSQL","description":"Learn how to build a RESTful API in Python using Flask and PostgreSQL. Step-by-step guide to creating, managing, and securing APIs with database integration.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.talentelgia.com\/blog\/how-to-build-a-restful-api-in-python-using-flask-and-postgresql\/","og_locale":"en_US","og_type":"article","og_title":"How to Build a RESTful API in Python Using Flask and PostgreSQL","og_description":"Learn how to build a RESTful API in Python using Flask and PostgreSQL. Step-by-step guide to creating, managing, and securing APIs with database integration.","og_url":"https:\/\/www.talentelgia.com\/blog\/how-to-build-a-restful-api-in-python-using-flask-and-postgresql\/","og_site_name":"Talentelgia","article_published_time":"2024-12-10T12:29:19+00:00","article_modified_time":"2024-12-26T06:52:36+00:00","og_image":[{"width":1920,"height":1080,"url":"https:\/\/www.talentelgia.com\/blog\/wp-content\/uploads\/2024\/12\/How-to-build-Restful-API-.webp","type":"image\/webp"}],"author":"Amandeep Singh","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Amandeep Singh","Est. reading time":"3 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.talentelgia.com\/blog\/how-to-build-a-restful-api-in-python-using-flask-and-postgresql\/#article","isPartOf":{"@id":"https:\/\/www.talentelgia.com\/blog\/how-to-build-a-restful-api-in-python-using-flask-and-postgresql\/"},"author":{"name":"Amandeep Singh","@id":"https:\/\/www.talentelgia.com\/blog\/#\/schema\/person\/44b9de9c8d4826795325996e579d67e8"},"headline":"How to Build a RESTful API in Python Using Flask and PostgreSQL","datePublished":"2024-12-10T12:29:19+00:00","dateModified":"2024-12-26T06:52:36+00:00","mainEntityOfPage":{"@id":"https:\/\/www.talentelgia.com\/blog\/how-to-build-a-restful-api-in-python-using-flask-and-postgresql\/"},"wordCount":508,"commentCount":0,"publisher":{"@id":"https:\/\/www.talentelgia.com\/blog\/#organization"},"image":{"@id":"https:\/\/www.talentelgia.com\/blog\/how-to-build-a-restful-api-in-python-using-flask-and-postgresql\/#primaryimage"},"thumbnailUrl":"https:\/\/www.talentelgia.com\/blog\/wp-content\/uploads\/2024\/12\/How-to-build-Restful-API-.webp","articleSection":["Web Development"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/www.talentelgia.com\/blog\/how-to-build-a-restful-api-in-python-using-flask-and-postgresql\/","url":"https:\/\/www.talentelgia.com\/blog\/how-to-build-a-restful-api-in-python-using-flask-and-postgresql\/","name":"How to Build a RESTful API in Python Using Flask and PostgreSQL","isPartOf":{"@id":"https:\/\/www.talentelgia.com\/blog\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.talentelgia.com\/blog\/how-to-build-a-restful-api-in-python-using-flask-and-postgresql\/#primaryimage"},"image":{"@id":"https:\/\/www.talentelgia.com\/blog\/how-to-build-a-restful-api-in-python-using-flask-and-postgresql\/#primaryimage"},"thumbnailUrl":"https:\/\/www.talentelgia.com\/blog\/wp-content\/uploads\/2024\/12\/How-to-build-Restful-API-.webp","datePublished":"2024-12-10T12:29:19+00:00","dateModified":"2024-12-26T06:52:36+00:00","description":"Learn how to build a RESTful API in Python using Flask and PostgreSQL. Step-by-step guide to creating, managing, and securing APIs with database integration.","breadcrumb":{"@id":"https:\/\/www.talentelgia.com\/blog\/how-to-build-a-restful-api-in-python-using-flask-and-postgresql\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.talentelgia.com\/blog\/how-to-build-a-restful-api-in-python-using-flask-and-postgresql\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.talentelgia.com\/blog\/how-to-build-a-restful-api-in-python-using-flask-and-postgresql\/#primaryimage","url":"https:\/\/www.talentelgia.com\/blog\/wp-content\/uploads\/2024\/12\/How-to-build-Restful-API-.webp","contentUrl":"https:\/\/www.talentelgia.com\/blog\/wp-content\/uploads\/2024\/12\/How-to-build-Restful-API-.webp","width":1920,"height":1080,"caption":"Build a RESTful API in Python Using Flask and PostgreSQL"},{"@type":"BreadcrumbList","@id":"https:\/\/www.talentelgia.com\/blog\/how-to-build-a-restful-api-in-python-using-flask-and-postgresql\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.talentelgia.com\/blog\/"},{"@type":"ListItem","position":2,"name":"How to Build a RESTful API in Python Using Flask and PostgreSQL"}]},{"@type":"WebSite","@id":"https:\/\/www.talentelgia.com\/blog\/#website","url":"https:\/\/www.talentelgia.com\/blog\/","name":"Talentelgia","description":"Latest Web &amp; Mobile Technologies, AI\/ML, and Blockchain Blogs","publisher":{"@id":"https:\/\/www.talentelgia.com\/blog\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.talentelgia.com\/blog\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/www.talentelgia.com\/blog\/#organization","name":"Talentelgia","url":"https:\/\/www.talentelgia.com\/blog\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.talentelgia.com\/blog\/#\/schema\/logo\/image\/","url":"https:\/\/www.talentelgia.com\/blog\/wp-content\/uploads\/2024\/01\/talentelgia-logo.svg","contentUrl":"https:\/\/www.talentelgia.com\/blog\/wp-content\/uploads\/2024\/01\/talentelgia-logo.svg","width":159,"height":53,"caption":"Talentelgia"},"image":{"@id":"https:\/\/www.talentelgia.com\/blog\/#\/schema\/logo\/image\/"}},{"@type":"Person","@id":"https:\/\/www.talentelgia.com\/blog\/#\/schema\/person\/44b9de9c8d4826795325996e579d67e8","name":"Amandeep Singh","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.talentelgia.com\/blog\/#\/schema\/person\/image\/","url":"https:\/\/www.talentelgia.com\/blog\/wp-content\/uploads\/2024\/11\/7EB3EE9B-4D5A-4F47-AB90-55A574FF9FE6-150x150.webp","contentUrl":"https:\/\/www.talentelgia.com\/blog\/wp-content\/uploads\/2024\/11\/7EB3EE9B-4D5A-4F47-AB90-55A574FF9FE6-150x150.webp","caption":"Amandeep Singh"},"description":"Amandeep is a dedicated tech enthusiast with a passion for simplifying complex concepts. With a keen eye for emerging technologies and a knack for sharing knowledge, he breaks down intricate tech topics into easy-to-understand explanations with his blogs. With a keen interest in emerging technologies, Amandeep strives to make technology accessible to everyone.","sameAs":["https:\/\/www.linkedin.com\/company\/talentelgia-technologies\/"],"url":"https:\/\/www.talentelgia.com\/blog\/author\/amandeep-singh\/"}]}},"_links":{"self":[{"href":"https:\/\/www.talentelgia.com\/blog\/wp-json\/wp\/v2\/posts\/3801","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.talentelgia.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.talentelgia.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.talentelgia.com\/blog\/wp-json\/wp\/v2\/users\/6"}],"replies":[{"embeddable":true,"href":"https:\/\/www.talentelgia.com\/blog\/wp-json\/wp\/v2\/comments?post=3801"}],"version-history":[{"count":15,"href":"https:\/\/www.talentelgia.com\/blog\/wp-json\/wp\/v2\/posts\/3801\/revisions"}],"predecessor-version":[{"id":4130,"href":"https:\/\/www.talentelgia.com\/blog\/wp-json\/wp\/v2\/posts\/3801\/revisions\/4130"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.talentelgia.com\/blog\/wp-json\/wp\/v2\/media\/3892"}],"wp:attachment":[{"href":"https:\/\/www.talentelgia.com\/blog\/wp-json\/wp\/v2\/media?parent=3801"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.talentelgia.com\/blog\/wp-json\/wp\/v2\/categories?post=3801"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.talentelgia.com\/blog\/wp-json\/wp\/v2\/tags?post=3801"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}