{"id":7453,"date":"2024-04-11T12:29:39","date_gmt":"2024-04-11T12:29:39","guid":{"rendered":"https:\/\/blog.ssdnodes.com\/blog\/?p=7453"},"modified":"2025-05-18T19:30:04","modified_gmt":"2025-05-18T19:30:04","slug":"flask-restful-api-tutorial","status":"publish","type":"post","link":"https:\/\/www.ssdnodes.com\/blog\/flask-restful-api-tutorial\/","title":{"rendered":"Python Flask RESTful API Example Tutorial"},"content":{"rendered":"<p>Seeking a beginner-friendly Python Flask RESTful API tutorial? Look no further, you're in the right place!<\/p>\n<h2>Python Flask RESTful API Tutorial - Introduction<\/h2>\n<p>In this guide, I will show you exactly how to create Flask RESTful APIs with an easy-to-understand example.<\/p>\n<p>The example RESTful API you will create in this tutorial will allow you to add text messages to a file using an HTTP POST request, and display them with a GET request.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-8887\" src=\"https:\/\/www.ssdnodes.com\/wp-content\/uploads\/2024\/03\/Flask-RESTful-API-Tutorial-1.png\" alt=\"Python Flask RESTful API Tutorial \" width=\"600\" height=\"400\" srcset=\"https:\/\/www.ssdnodes.com\/wp-content\/uploads\/2024\/03\/Flask-RESTful-API-Tutorial-1.png 768w, https:\/\/www.ssdnodes.com\/wp-content\/uploads\/2024\/03\/Flask-RESTful-API-Tutorial-1-300x200.png 300w\" sizes=\"auto, (max-width: 600px) 100vw, 600px\" \/><\/p>\n<h2>What is Flask?<\/h2>\n<p>Flask is a Python web framework that allows you to create web applications and RESTful APIs using the Python language.<\/p>\n<h2>What is a RESTful API?<\/h2>\n<p>A <a href=\"https:\/\/en.wikipedia.org\/wiki\/REST\" target=\"_blank\" rel=\"noopener\">RESTful API<\/a> (Representational State Transfer) is a set of rules that developers follow when they create their <a href=\"https:\/\/adyouri.com\/what-is-an-api-in-simple-terms\" target=\"_blank\" rel=\"noopener\">API<\/a>. It's based on the idea of making requests to resources on a server, where each resource is uniquely identified by a URL (Uniform Resource Locator).<\/p>\n<p>In simple terms, think of it as ordering food from a menu in a restaurant. You choose what you want from the menu (the resource), place an order (send a request), and then you receive your food (get a response).<\/p>\n<h2>Python Flask RESTful API Tutorial - Prerequisites<\/h2>\n<p>To follow this tutorial you need:<\/p>\n<ul>\n<li>Basic knowledge of the Linux command line.<\/li>\n<li>An Ubuntu 22.04 server with a non-root user with <code>sudo<\/code> privileges. You can get affordable, and powerful Ubuntu servers from <a href=\"https:\/\/www.ssdnodes.com\/\" target=\"external\">our website<\/a>, and you can check out our <a href=\"https:\/\/www.ssdnodes.com\/blog\/tutorial-setting-up-and-securing-ssh-based-authentication\/\">How to access your server using SSH<\/a> guide to learn how to access your server and create a <code>sudo<\/code> user.<\/li>\n<li>Basic knowledge of the Python programming language.<\/li>\n<\/ul>\n<h2>Step 1 - Update The Package Cache<\/h2>\n<p>To get the latest packages, start by updating the packages in the package manager cache to the latest available versions using the following command:<\/p>\n<pre><code>sudo apt update<\/code><\/pre>\n<h3>Output<\/h3>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-8888 size-full\" src=\"https:\/\/www.ssdnodes.com\/wp-content\/uploads\/2024\/03\/sudo-apt-update-1.png\" alt=\"Flask RESTful API Tutorial: Updating Packages\" width=\"600\" height=\"253\" srcset=\"https:\/\/www.ssdnodes.com\/wp-content\/uploads\/2024\/03\/sudo-apt-update-1.png 600w, https:\/\/www.ssdnodes.com\/wp-content\/uploads\/2024\/03\/sudo-apt-update-1-300x127.png 300w\" sizes=\"auto, (max-width: 600px) 100vw, 600px\" \/><\/p>\n<h2>Step 2 - Installing Core Dependencies<\/h2>\n<p>Before you start coding your Flask RESTful API, you need to install some core dependencies for your Python programming environment. To do this, use the following command:<\/p>\n<pre><code>sudo apt install python3-pip python3-dev build-essential libssl-dev libffi-dev python3-setuptools python3-venv<\/code><\/pre>\n<h3>Output<\/h3>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-8889\" src=\"https:\/\/www.ssdnodes.com\/wp-content\/uploads\/2024\/03\/install-deps-1.png\" alt=\"Python Flask RESTful API Tutorial: Installing Dependencies \" width=\"600\" height=\"235\" srcset=\"https:\/\/www.ssdnodes.com\/wp-content\/uploads\/2024\/03\/install-deps-1.png 600w, https:\/\/www.ssdnodes.com\/wp-content\/uploads\/2024\/03\/install-deps-1-300x118.png 300w\" sizes=\"auto, (max-width: 600px) 100vw, 600px\" \/><\/p>\n<p>With this, you can now create a Python virtual environment for your project.<\/p>\n<h2>Step 3 - Isolating your Flask RESTful API in a Virtual Environment<\/h2>\n<p>Before you install Flask, you will first create a project folder and then create a Python virtual environment inside it to isolate your project code and dependencies from the rest of the system.<\/p>\n<p>Python virtual environments allow you to have multiple isolated Python environments on one computer. This is useful for projects that require different versions of Python, or for projects that you don't want to contaminate with code from other projects. This ensures that each Python project is isolated from your other projects, so that conflict between dependencies does not occur.<\/p>\n<p>First, create the project folder, we'll call it <code>myapp<\/code>:<\/p>\n<pre><code>mkdir myapp<\/code><\/pre>\n<p>Navigate to it:<\/p>\n<pre><code>cd myapp<\/code><\/pre>\n<p>Create a Python virtual environment inside your <code>myapp<\/code> project folder:<\/p>\n<pre><code>python3 -m venv env<\/code><\/pre>\n<p>Activate it:<\/p>\n<pre><code>source env\/bin\/activate<\/code><\/pre>\n<p>Your command line should now have an <code>(env)<\/code> prefix indicating that your virtual environment is activated.<\/p>\n<p>Install Flask:<\/p>\n<pre><code>pip install flask<\/code><\/pre>\n<h3>Output<\/h3>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-8890\" src=\"https:\/\/www.ssdnodes.com\/wp-content\/uploads\/2024\/03\/flask-install-success-1.png\" alt=\"Python Flask RESTful API Tutorial: Installing Flask\" width=\"600\" height=\"235\" srcset=\"https:\/\/www.ssdnodes.com\/wp-content\/uploads\/2024\/03\/flask-install-success-1.png 600w, https:\/\/www.ssdnodes.com\/wp-content\/uploads\/2024\/03\/flask-install-success-1-300x118.png 300w\" sizes=\"auto, (max-width: 600px) 100vw, 600px\" \/><\/p>\n<p>With Flask now installed, you can now create a small application.<\/p>\n<h2>Step 4 - Building a Small Flask Application to Test Our Installation<\/h2>\n<p>First, we'll create a small Flask application that displays a <code>Hello World!<\/code> web page using a single Python file to test that everything works.<\/p>\n<p>In your <code>myapp<\/code> folder, open a file called <code>app.py<\/code>:<\/p>\n<pre><code>nano app.py<\/code><\/pre>\n<p>Add the following code to it:<\/p>\n<pre><code>from flask import Flask\r\napp = Flask(__name__)\r\n\r\n@app.route('\/')\r\ndef hello():\r\n    return '&lt;h1&gt;Hello World! This is my Flask Application!&lt;\/h1&gt;'\r\n\r\nif __name__ == \"__main__\":\r\n    app.run(host='0.0.0.0')<\/code><\/pre>\n<p>This code uses the Flask class to display an <code>H1<\/code> heading on the main route (<code>\/<\/code>).<\/p>\n<p>Save and close the file.<\/p>\n<p>If you've set up a firewall using UFW, you need to allow access to port <code>5000<\/code>, which is the port Flask uses:<\/p>\n<pre><code>sudo ufw allow 5000<\/code><\/pre>\n<p>Next, run your application using the following command:<\/p>\n<pre><code>python app.py<\/code><\/pre>\n<p>You will get the following output, which gives information on your application and warns you not to use this simple Flask server on a production environment:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-8891\" src=\"https:\/\/www.ssdnodes.com\/wp-content\/uploads\/2024\/03\/app-run-output-1.png\" alt=\"Flask Development Server\" width=\"600\" height=\"346\" srcset=\"https:\/\/www.ssdnodes.com\/wp-content\/uploads\/2024\/03\/app-run-output-1.png 600w, https:\/\/www.ssdnodes.com\/wp-content\/uploads\/2024\/03\/app-run-output-1-300x173.png 300w\" sizes=\"auto, (max-width: 600px) 100vw, 600px\" \/><\/p>\n<p>You can now visit your application's web page using your server's IP address and the <code>5000<\/code> port. Use your browser and navigate to the following URL:<\/p>\n<pre><code>http:\/\/your_server_ip:5000<\/code><\/pre>\n<p>You'll see the <code>Hello World! This is my Flask Application!<\/code> header on your browser.<\/p>\n<p>To terminate the flask application, tap <code>CTRL-C<\/code> in your terminal to stop the Flask development server.<\/p>\n<h2>Step 5 - Creating a Flask POST Endpoint for the RESTful API<\/h2>\n<p>The first part of our Flask RESTful API involves creating a new <strong>Flask POST endpoint<\/strong> that accepts POST requests and adds a new message to a text database.<\/p>\n<p>First, open your <code>app.py<\/code> file for modification:<\/p>\n<pre><code>nano app.py<\/code><\/pre>\n<p>Add the following highlighted parts:<\/p>\n<pre><code>import json\r\nfrom flask import Flask<mark>, request, jsonify<\/mark>\r\napp = Flask(__name__)\r\n\r\n@app.route('\/')\r\ndef hello():\r\n    return '&lt;h1&gt;Hello World! This is my Flask Application!&lt;\/h1&gt;'\r\n\r\n<mark>\r\n@app.post('\/api\/')\r\ndef add_message():\r\n    message = json.loads(request.data)\r\n    with open('data.json', 'r') as f:\r\n        data = f.read()\r\n\r\n    # If no data is in the text file, create a new list\r\n    if not data:\r\n        messages = [message]\r\n    # If data exists in the text file, load it into a list\r\n    # then append the new message to it\r\n    else:\r\n        messages = json.loads(data)\r\n        messages.append(message)\r\n\r\n    with open('data.json', 'w') as f:\r\n        f.write(json.dumps(messages, indent=2))\r\n\r\n    # return the added message\r\n    return jsonify(message), 201\r\n<\/mark>\r\nif __name__ == \"__main__\":\r\n    app.run(host='0.0.0.0')<\/code><\/pre>\n<p>Save and close the file.<\/p>\n<p>Here, you imported the <code>json<\/code> Python module, and the <code>request<\/code> and <code>jsonify<\/code> helpers from the Flask package.<\/p>\n<p>You added the route <code>@app.post('\/api\/')<\/code> which accepts POST requests, hence why you use the <code>@app.post<\/code> decorator instead of the standard <code>@app.route()<\/code>.<\/p>\n<p>In the <code>add_message()<\/code> view function, you use <code>json.loads()<\/code> to load the POST request data as JSON into a variable called <code>message<\/code>, then you open a file called <code>data.json<\/code> and read it and save its contents in the <code>data<\/code> variable. For now, the <code>data.json<\/code> file does not exist yet, but you will create it later. If <code>data.json<\/code> is empty, you create a <code>messages<\/code> list with the POST request data that's in the <code>message<\/code> variable.<\/p>\n<p>If there is already a list of JSON messages in the <code>data.json<\/code> file, you load it into the <code>messages<\/code> variable, and then append the new message in the POST request to it.<\/p>\n<p>Next, you open the <code>data.json<\/code> file for writing, and then you write the messages into it.<\/p>\n<p>Finally, you return the submitted message in a JSON format as a response with the <code>201<\/code> HTTP status which indicates that the request succeeded, and a new resource was created as a result.<\/p>\n<p>Create the data file:<\/p>\n<pre><code>touch data.json<\/code><\/pre>\n<p>Then run the server:<\/p>\n<pre><code>python app.py<\/code><\/pre>\n<p>Now, send a POST request with a message and a name using <code>curl<\/code>:<\/p>\n<pre><code>curl -X POST -d '{\"name\":\"mike\", \"message\": \"Hello there!\"}' http:\/\/your_IP:5000\/api\/ -H \"Content-Type: application\/json\"<\/code><\/pre>\n<p>Remember to change <code>your_IP<\/code> to your server's IP address.<\/p>\n<p>You should receive the following response:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-8892 size-full\" src=\"https:\/\/www.ssdnodes.com\/wp-content\/uploads\/2024\/03\/json-response-1.png\" alt=\"Flask POST Endpoint in Flask RESTful API\" width=\"600\" height=\"198\" srcset=\"https:\/\/www.ssdnodes.com\/wp-content\/uploads\/2024\/03\/json-response-1.png 600w, https:\/\/www.ssdnodes.com\/wp-content\/uploads\/2024\/03\/json-response-1-300x99.png 300w\" sizes=\"auto, (max-width: 600px) 100vw, 600px\" \/><\/p>\n<p>You can use the same command to add more messages:<\/p>\n<pre><code>curl -X POST -d '{\"name\":\"john\", \"message\": \"Hello Everyone! My name is John!\"}' http:\/\/your_IP:5000\/api\/ -H \"Content-Type: application\/json\"<\/code><\/pre>\n<p>Now that you've added a few messages using a POST request, you will create a route to display all the messages in your database using a GET request next.<\/p>\n<h2>Step 6 - Creating a Flask GET Endpoint for the RESTful API<\/h2>\n<p>Now that you have a method for adding new messages, the second part of our Flask RESTful API involves creating a new <strong>Flask GET endpoint<\/strong> that accepts GET requests and displays messages in a JSON format.<\/p>\n<p>To display the messages in the <code>data.json<\/code> file, you can simply use <code>cat<\/code> to read the file:<\/p>\n<pre><code>cat data.json<\/code><\/pre>\n<p>You should see the following output:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-8893\" src=\"https:\/\/www.ssdnodes.com\/wp-content\/uploads\/2024\/03\/GET-output-1.png\" alt=\"Flask GET Endpoint in Flask RESTful API\" width=\"600\" height=\"365\" srcset=\"https:\/\/www.ssdnodes.com\/wp-content\/uploads\/2024\/03\/GET-output-1.png 600w, https:\/\/www.ssdnodes.com\/wp-content\/uploads\/2024\/03\/GET-output-1-300x183.png 300w\" sizes=\"auto, (max-width: 600px) 100vw, 600px\" \/><\/p>\n<p>Now, you can create a new route in your <code>app.py<\/code> file that returns the contents of your <code>data.json<\/code> database file as a JSON response.<\/p>\n<p>First, open <code>app.py<\/code> for modification:<\/p>\n<pre><code>nano app.py<\/code><\/pre>\n<p>Add the following route before the <code>if __name__ == \"__main__\":<\/code> line of your <code>app.py<\/code> file:<\/p>\n<pre><code>@app.get('\/api\/')\r\ndef display_messages():\r\n    with open('data.json', 'r') as f:\r\n        data = f.read()\r\n        if not data:\r\n                return jsonify({'error': 'data not found'}), 404\r\n        messages = json.loads(data)\r\n\r\n    return jsonify(messages)<\/code><\/pre>\n<p>Save and close the file.<\/p>\n<p>Here, you use the <code>@app.get()<\/code> decorator to respond to GET requests that are sent to the <code>\/api\/<\/code> route. In the <code>display_messages()<\/code> view function, you open the <code>data.json<\/code> and read it, if it's empty, you return an error message as a JSON response indicating that the data was not found along with a <code>404<\/code> HTTP status code. Otherwise you load the data into the <code>messages<\/code> variable and return it as a response.<\/p>\n<p>Now, you can test this new route using <code>curl<\/code> by sending a GET request to the <code>\/api\/<\/code> route:<\/p>\n<pre><code>curl http:\/\/your_IP:5000\/api\/<\/code><\/pre>\n<p>You should receive the messages you previously added to your database as a JSON response:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-8894\" src=\"https:\/\/www.ssdnodes.com\/wp-content\/uploads\/2024\/03\/curl-get-output-1.png\" alt=\"Flask GET Endpoint in Flask RESTful API - Curl Example\" width=\"600\" height=\"235\" srcset=\"https:\/\/www.ssdnodes.com\/wp-content\/uploads\/2024\/03\/curl-get-output-1.png 600w, https:\/\/www.ssdnodes.com\/wp-content\/uploads\/2024\/03\/curl-get-output-1-300x118.png 300w\" sizes=\"auto, (max-width: 600px) 100vw, 600px\" \/><\/p>\n<p>With this, you now have a small RESTful API that can be used to add and retrieve messages.<\/p>\n<h2>Note<\/h2>\n<p>This was a simple demonstration of how to create a RESTful API with Flask, in which you used a simple JSON file as a database. However, using a JSON file as a database in the real world is extremely inefficient and cumbersome. Therefore, you need to use an SQL or NoSQL database instead such as SQLite, PostgreSQL, or MongoDB.<\/p>\n<h2>Conclusion<\/h2>\n<p>In this tutorial, you've learned how to create a simple RESTful API with Flask in Python. You built a RESTful API that receives data via POST requests, and gets data using GET requests.<\/p>\n<h2>FAQ: Questions on Python Flask RESTful APIs<\/h2>\n<h3>What are some best practices for designing and developing Flask RESTful APIs?<\/h3>\n<p>Here are some best practices for developing RESTful APIs in Flask:<\/p>\n<ul>\n<li>Ensure meaningful resource URIs.<\/li>\n<li>Adhere to RESTful principles like using proper HTTP methods.<\/li>\n<li>Document API endpoints comprehensively.<\/li>\n<li>Implement security measures such as authentication and authorization to protect against unauthorized access.<\/li>\n<\/ul>\n<h3>How does Flask differ from other frameworks for building RESTful APIs?<\/h3>\n<p>Flask offers simplicity and flexibility, allowing developers to build lightweight APIs quickly, whereas other frameworks might be more opinionated or complex.<\/p>\n<h3>Is Flask suitable for building large-scale production-ready RESTful APIs?<\/h3>\n<p>Yes, Flask can be used to build large-scale, production-ready RESTful APIs when combined with best practices such as modular code organization, efficient database management, and robust testing. By following industry standards and leveraging Flask's extensibility, you can create scalable and reliable APIs that meet the demands of your application's users.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Master Flask RESTful APIs: Beginner-friendly tutorial series for building, testing, &#038; deploying your own API step-by-step. Unleash Python power with Flask!<\/p>\n","protected":false},"author":19,"featured_media":8841,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"inline_featured_image":false,"footnotes":""},"categories":[18,30],"tags":[],"class_list":["post-7453","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-devops","category-tutorials"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.ssdnodes.com\/wp-json\/wp\/v2\/posts\/7453","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.ssdnodes.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.ssdnodes.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.ssdnodes.com\/wp-json\/wp\/v2\/users\/19"}],"replies":[{"embeddable":true,"href":"https:\/\/www.ssdnodes.com\/wp-json\/wp\/v2\/comments?post=7453"}],"version-history":[{"count":19,"href":"https:\/\/www.ssdnodes.com\/wp-json\/wp\/v2\/posts\/7453\/revisions"}],"predecessor-version":[{"id":13051,"href":"https:\/\/www.ssdnodes.com\/wp-json\/wp\/v2\/posts\/7453\/revisions\/13051"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.ssdnodes.com\/wp-json\/wp\/v2\/media\/8841"}],"wp:attachment":[{"href":"https:\/\/www.ssdnodes.com\/wp-json\/wp\/v2\/media?parent=7453"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.ssdnodes.com\/wp-json\/wp\/v2\/categories?post=7453"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.ssdnodes.com\/wp-json\/wp\/v2\/tags?post=7453"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}