Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to write a simple Flask API for hello world?
Flask is a lightweight web framework written in Python that allows developers to quickly build web applications and APIs. It provides a simple and elegant way to create RESTful APIs with minimal code. In this article, we will walk through the process of creating a simple Flask API that returns a "Hello, World!" message.
Prerequisites
Before we start, make sure you have the following installed on your machine:
Python (version 3.6 or above)
Flask (can be installed using pip)
Algorithm
A generic algorithm for writing any simple Flask API is as follows:
Set up the Flask environment by creating a new project directory
Create and activate a virtual environment
Install Flask using pip
Write the Flask API code with routes and functions
Run the Flask development server
Test the API endpoints
Steps for Creating a Simple Flask API
Step 1: Setting up the Flask Environment
Create a new directory for our project and navigate to it ?
mkdir flask-api-hello-world cd flask-api-hello-world
Step 2: Creating a Virtual Environment
It is considered good practice to work within a virtual environment to avoid conflicts between different project dependencies. Create a virtual environment using the following command ?
python3 -m venv venv
Activate the virtual environment ?
On macOS/Linux:
source venv/bin/activate
On Windows:
venv\Scripts\activate
Step 3: Installing Flask
Once inside the virtual environment, install Flask using pip ?
pip install flask
Step 4: Writing the Flask API
Create a Python file named app.py and add the following code to create a basic Flask API ?
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
@app.route('/api/hello')
def api_hello():
return {'message': 'Hello, World!', 'status': 'success'}
if __name__ == '__main__':
app.run(debug=True)
In this code, we import the Flask module, create a Flask application instance, and define two routes. The @app.route('/') decorator creates a route for the root URL, while @app.route('/api/hello') creates an API endpoint that returns JSON data.
Step 5: Running the Flask API
Save the app.py file and run the Flask development server ?
python app.py
You should see output similar to the following ?
* Running on http://127.0.0.1:5000 * Debug mode: on * Restarting with stat * Debugger is active!
Step 6: Testing the Flask API
Open a web browser and navigate to the following URLs to test your API ?
http://127.0.0.1:5000/ Returns plain text "Hello, World!"
http://127.0.0.1:5000/api/hello Returns JSON response
The JSON endpoint will return ?
{
"message": "Hello, World!",
"status": "success"
}
Adding More Routes
You can easily add more routes to your Flask API ?
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
@app.route('/api/hello')
def api_hello():
return jsonify({'message': 'Hello, World!', 'status': 'success'})
@app.route('/api/users')
def get_users():
users = [
{'id': 1, 'name': 'Alice'},
{'id': 2, 'name': 'Bob'}
]
return jsonify(users)
if __name__ == '__main__':
app.run(debug=True)
The /api/users endpoint returns a list of users in JSON format. Using jsonify() ensures proper JSON response headers.
Conclusion
We successfully created a simple Flask API that returns "Hello, World!" messages in both text and JSON formats. Flask's decorator-based routing system makes it easy to create multiple endpoints and build RESTful APIs quickly.
