Building a Simple API with Flask in Python

Building a Simple API with Flask in Python. Flask is a lightweight WSGI web application framework in Python, renowned for its simplicity, flexibility, and fine-grained control. It makes it easy to build with applications and APIs which are essential for backend web services. In this tutorial, we will introduce creating a basic API using Flask enabling you to serve data over the internet in a structured format(JSON in our case).

Setting Environment

Before writing code for our Flask application, ensure that you have installed Python on your system. You will also need Flask, which you can install using pip, Python’s package installer. Open your terminal or command prompt and run the following command.

Creating a Simple Flask API

Initialize your Flask Application

Create a new file named, and open it in your favorite code editor. Begin by importing Flask and initializing your Flask application.

Define a Route in Flask

Routes in Flask are used to direct users to different parts of your application based on the URL. Let’s create a simple route in Flask that returns a message.

Running your Flask Application

To run your Flask application, add the following line at the end of your app.py file.

The debug = True parameter allows your application to automatically reload upon code changes, which is helpful during development.

Now run your application by executing this following command.

Your Flask server will start and you can access your route by navigating to http://127.0.0.1:5000 in your web browser.

Flask Application

Creating a JSON API Endpoint with Flask

APIs commonly return data in JSON format. Let’s modify our application to return a simple JSON response.

First, import Flask’s jsonify function.

Now create a new route that returns JSON data-

Testing API

With your Flask application running, access your new API endpoint by navigating to http://127.0.0.1:5000/api/data In your web browser or using tools like postman, etc. You should see the JSON response.

Creating a JSON API Endpoint with Flask

Flask offers a straightforward path to developing web applications and APIs, making it an excellent choice for beginners and experienced developers alike. By following this guide, you have learned the basics of setting up a Flask application and creating a simple API. As you become more comfortable with Flask, you will discover it is capable of supporting complex web applications with numerous routes, templates, and integrations.

Happy Coding & Learning

See Also

1 thought on “Building a Simple API with Flask in Python”

Leave a Comment