{"id":10688,"date":"2025-10-28T03:32:56","date_gmt":"2025-10-28T03:32:56","guid":{"rendered":"https:\/\/namastedev.com\/blog\/?p=10688"},"modified":"2025-10-28T03:32:56","modified_gmt":"2025-10-28T03:32:56","slug":"building-a-simple-rest-api-with-pythons-flask-and-a-sql-database","status":"publish","type":"post","link":"https:\/\/namastedev.com\/blog\/building-a-simple-rest-api-with-pythons-flask-and-a-sql-database\/","title":{"rendered":"Building a Simple REST API with Python&#8217;s Flask and a SQL Database"},"content":{"rendered":"<h1>Building a Simple REST API with Python&#8217;s Flask and a SQL Database<\/h1>\n<p>In today&#8217;s tech landscape, RESTful APIs are essential for enabling interactions between different applications and systems. In this tutorial, we\u2019ll walk you through creating a simple REST API using Python&#8217;s Flask framework and a SQL database for data storage. Whether you are a beginner hoping to level up your skills or an experienced developer looking for a refresher, this guide has something for you.<\/p>\n<h2>What is Flask?<\/h2>\n<p>Flask is a lightweight web framework for Python that promotes rapid development and a clean codebase. It\u2019s easy to get started with and is highly extensible for more complex applications. Flask follows the WSGI (Web Server Gateway Interface) standard and is categorized as a micro-framework due to its minimalistic approach.<\/p>\n<h2>Why Use a SQL Database?<\/h2>\n<p>A SQL database provides a structured way to store data using tables, allowing for efficient querying and data manipulation. Popular SQL databases like SQLite, PostgreSQL, and MySQL are widely supported and well-documented, making them an excellent option for backend data management in web applications.<\/p>\n<h2>Prerequisites<\/h2>\n<p>Before we begin, ensure you have the following installed:<\/p>\n<ul>\n<li>Python 3.x<\/li>\n<li>Flask<\/li>\n<li>SQLAlchemy<\/li>\n<li>A SQLite database (or any SQL database of your choice)<\/li>\n<\/ul>\n<h2>Step 1: Setting Up Your Environment<\/h2>\n<p>First, let\u2019s create a virtual environment and install Flask and the SQLAlchemy package for ORM access:<\/p>\n<pre><code>mkdir flask-api\ncd flask-api\npython -m venv venv\nsource venv\/bin\/activate  # For Windows use venvScriptsactivate\npip install Flask SQLAlchemy<\/code><\/pre>\n<h2>Step 2: Project Structure<\/h2>\n<p>Your project structure will look like this:<\/p>\n<pre><code>flask-api\/\n\u2502\n\u251c\u2500\u2500 app.py\n\u2514\u2500\u2500 models.py\n<\/code><\/pre>\n<h2>Step 3: Creating Your Database Model<\/h2>\n<p>Next, let\u2019s create a simple data model for a task management API. In this case, we will create a &#8220;Task&#8221; model with fields for the task ID, title, and status.<\/p>\n<pre><code># models.py\nfrom flask_sqlalchemy import SQLAlchemy\n\ndb = SQLAlchemy()\n\nclass Task(db.Model):\n    id = db.Column(db.Integer, primary_key=True)\n    title = db.Column(db.String(150), nullable=False)\n    completed = db.Column(db.Boolean, default=False)\n\n    def __repr__(self):\n        return f\"\"<\/code><\/pre>\n<h2>Step 4: Initializing Flask and Connecting to the Database<\/h2>\n<p>Now, let&#8217;s set up Flask and connect our application to the SQLite database.<\/p>\n<pre><code># app.py\nfrom flask import Flask, jsonify, request\nfrom models import db, Task\n\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:\/\/\/tasks.db'\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\ndb.init_app(app)\n\nwith app.app_context():\n    db.create_all()  # Create tables\n\n@app.route('\/tasks', methods=['GET'])\ndef get_tasks():\n    tasks = Task.query.all()\n    return jsonify([{'id': task.id, 'title': task.title, 'completed': task.completed} for task in tasks]), 200\n<\/code><\/pre>\n<h2>Step 5: Adding API Endpoints<\/h2>\n<p>We will implement the following endpoints:<\/p>\n<ul>\n<li>GET \/tasks &#8211; Retrieve all tasks<\/li>\n<li>POST \/tasks &#8211; Create a new task<\/li>\n<li>PUT \/tasks\/&lt;id&gt; &#8211; Update an existing task<\/li>\n<li>DELETE \/tasks\/&lt;id&gt; &#8211; Delete a task<\/li>\n<\/ul>\n<h3>GET Endpoint<\/h3>\n<p>We have already defined the GET endpoint to fetch all tasks. Now, let\u2019s add the POST endpoint to create new tasks.<\/p>\n<pre><code>@app.route('\/tasks', methods=['POST'])\ndef create_task():\n    data = request.get_json()\n    new_task = Task(title=data['title'])\n    db.session.add(new_task)\n    db.session.commit()\n    return jsonify({'id': new_task.id, 'title': new_task.title}), 201<\/code><\/pre>\n<h3>PUT Endpoint<\/h3>\n<p>Now, let\u2019s implement the PUT endpoint to update an existing task&#8217;s status or title.<\/p>\n<pre><code>@app.route('\/tasks\/&lt;int:id&gt;', methods=['PUT'])\ndef update_task(id):\n    task = Task.query.get_or_404(id)\n    data = request.get_json()\n    task.title = data.get('title', task.title)\n    task.completed = data.get('completed', task.completed)\n    db.session.commit()\n    return jsonify({'id': task.id, 'title': task.title, 'completed': task.completed}), 200<\/code><\/pre>\n<h3>DELETE Endpoint<\/h3>\n<p>Finally, let\u2019s create the DELETE endpoint.<\/p>\n<pre><code>@app.route('\/tasks\/&lt;int:id&gt;', methods=['DELETE'])\ndef delete_task(id):\n    task = Task.query.get_or_404(id)\n    db.session.delete(task)\n    db.session.commit()\n    return jsonify({'message': 'Task successfully deleted'}), 200<\/code><\/pre>\n<h2>Step 6: Testing Your API<\/h2>\n<p>To test the REST API, you can use tools like Postman or cURL. Here are some sample requests you could test:<\/p>\n<ul>\n<li>Get all tasks: <strong>GET \/tasks<\/strong><\/li>\n<li>Create a task: <strong>POST \/tasks<\/strong>\n<pre><code>{ \"title\": \"Buy groceries\" }<\/code><\/pre>\n<\/li>\n<li>Update a task: <strong>PUT \/tasks\/1<\/strong>\n<pre><code>{ \"completed\": true }<\/code><\/pre>\n<\/li>\n<li>Delete a task: <strong>DELETE \/tasks\/1<\/strong><\/li>\n<\/ul>\n<h2>Step 7: Improving Your API with Error Handling<\/h2>\n<p>For a robust API, implementing proper error handling is crucial. Here\u2019s how to return custom error messages:<\/p>\n<pre><code>@app.errorhandler(404)\ndef not_found(error):\n    return jsonify({'error': 'Not found'}), 404\n\n@app.errorhandler(400)\ndef bad_request(error):\n    return jsonify({'error': 'Bad request'}), 400<\/code><\/pre>\n<h2>Step 8: Running Your Application<\/h2>\n<p>Before running your API, ensure that you are still in the virtual environment. Use the following command to start the Flask application:<\/p>\n<pre><code>export FLASK_APP=app.py  # For Windows use set FLASK_APP=app.py\nflask run<\/code><\/pre>\n<p>Your API should now be up and running on <strong>http:\/\/127.0.0.1:5000<\/strong>.<\/p>\n<h2>Conclusion<\/h2>\n<p>Congratulations! You have built a simple REST API using Flask and a SQL database. This foundational knowledge can be expanded further by implementing features such as authentication, pagination, or integrating with front-end frameworks.<\/p>\n<p>As you continue your software development journey, remember that building RESTful APIs is a crucial skill that opens up a world of possibilities for connecting applications and services. Keep exploring and stay updated with best practices and emerging technologies!<\/p>\n<h2>Further Reading<\/h2>\n<ul>\n<li><a href=\"https:\/\/flask.palletsprojects.com\/en\/2.0.x\/\">Flask Documentation<\/a><\/li>\n<li><a href=\"https:\/\/docs.sqlalchemy.org\/en\/14\/\">SQLAlchemy Documentation<\/a><\/li>\n<li><a href=\"https:\/\/realpython.com\/flask-by-example-part-1-project-setup\/\">Flask by Example: Project Setup<\/a><\/li>\n<\/ul>\n<p>Happy coding!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Building a Simple REST API with Python&#8217;s Flask and a SQL Database In today&#8217;s tech landscape, RESTful APIs are essential for enabling interactions between different applications and systems. In this tutorial, we\u2019ll walk you through creating a simple REST API using Python&#8217;s Flask framework and a SQL database for data storage. Whether you are a<\/p>\n","protected":false},"author":91,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[266,280],"tags":[1039,1038,812,1290,1040],"class_list":["post-10688","post","type-post","status-publish","format-standard","category-back-end-development","category-sql-databases","tag-backend","tag-flask","tag-python","tag-sql-databases","tag-web-framework"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/10688","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/users\/91"}],"replies":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/comments?post=10688"}],"version-history":[{"count":1,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/10688\/revisions"}],"predecessor-version":[{"id":10689,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/10688\/revisions\/10689"}],"wp:attachment":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/media?parent=10688"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/categories?post=10688"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/tags?post=10688"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}