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).
Table of Contents
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.
pip install Flask
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.
from flask import Flask
app = Flask(__name__)
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.
@app.route('/')
def home():
return "Welcome to Flask API tutorial"
Running your Flask Application
To run your Flask application, add the following line at the end of your app.py file
.
if __name__ == '__main__':
app.run(debug = True)
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.
python app.py
Your Flask server will start and you can access your route by navigating to http://127.0.0.1:5000 in your web browser.
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.
from flask import Flask,jsonify
Now create a new route that returns JSON data-
@app.route('/api/data')
def jsonData():
return jsonify ({
'Topic': 'Flask',
'Message': 'Welocom to Flask API tutorial'
})
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.
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
1 thought on “Building a Simple API with Flask in Python”