Using Svelte.js with Flask backend server
In this blog post we will build a simple flask based API and connect it to Svelte front-end for an end-to-end application
Let’s start with the backend API. Basic understanding of Python venv environments is recommended but you can follow along without a virtual environment setup
Pre-Requisites
- Python 3.7+
- Flask
- venv (recommended)
Step 1: Creating a Flask API
- Create a new folder and activate the venv environment.
source env/bin/activate
- Install the Flask dependencies
pip install flask
- Validate the flask installation is complete
python -c "import flask; print(flask.__version__)"
- Finally, create a flask API as below (app.py) in the main folder
your file name might differ based on the setup and IDE of your choice
from flask import Flask, requestapp = Flask(__name__)@app.route('/message')
def generate_random():
args = request.args
print(args['name'])
return "Hello " + args['name']if __name__ == '__main__':
app.run()
- Finally, start the API by running the below command
python app.py
- Validate the API call by hitting the URL below
http://localhost:5000/message?name=manav
This should return with Hello manav
as the response
Step 2: Create a Svelte front-end
- Inside the main folder, create a new client-side folder and install svelte
npx degit sveltejs/template client
cd client
npm install
This will create a new svelte application and install the required dependencies. You can test the successful installation by running npm run dev
and browsing to http://localhost:5000
You should see a Hello World
in browser
- A svelte app is composed of
Svelte
components which are compiled at build time. You can read more about this on the svelte websitehttps://svelte.dev
- Next, find the default svelte component i.e.
App.svelte
in the generatedclient
folder and update the file code as below:
<script>
let message = '';
let src = '';async function getName() {
let thisMessage = message;
let res = await fetch(`./message?name=${message}`);
let message_received = await res.text();
if (res.ok && thisMessage == message) {
src = message_received;
}
}
</script><h1>Received Message: {src}!</h1>
<input type="text" placeholder="enter your name" bind:value={message} />
<button on:click={getName}>Send Message</button>
Here is a brief description of the code:
- We create an function
getName()
which makes aREST
call with aname
attribute with${message}
value - The function awaits the response received and extracts the text value
- If the
HTTP Response Code
is200 OK
the response is added to thesrc
variable - The
html
tags are required to capture the Entered Message, button for execution and finally to provide the generated response from the REST call
Step 3: Modify the Python class in Step 1 to load the client
side Svelte code
- Open
app.py
and add the following routes to the class
# Change to import `send_from_directory`
from flask import Flask, send_from_directory, request...# Path for our main Svelte page
@app.route("/")
def client():
return send_from_directory('client/public', 'index.html')
This will allow the index.html
file from client/public
folder on the root-context
Optionally, you can add the below route to load static content like JS files, CSS etc.
# Route to add static files (CSS and JS)
@app.route("/<path:path>")
def base(path):
return send_from_directory('client/public', path)
Step 4: Run the app
- Svelte app can be compiled by running
npm run build
from within theclient
folder - Finally, run the python app by running
python app.py
- Browse to
http://127.0.0.1:5000
; enter a name and clickSend Message
button - Message Received should show
Hello
name