DEV Community

Jack Henza
Jack Henza

Posted on

First Fullstack App

Introduction

Embarking on the journey of building a full stack web application has been both challenging and rewarding. In this blog post, we'll explore the process of creating a modern full stack app using Flask, SQLAlchemy, React, and Vite. Each of these technologies plays a crucial role in different layers of the application, combining to deliver a seamless and performant user experience. Other technologies could easily be incorporated, such as tailwind css, flowbite, or bootstrap. Various hosting services can be used, like render, netlify, or even supabase.

Getting Started

We'll be separating our codebase into two main divisions: server and client. Go ahead and create your server directory now, but don't cd into it in your terminal yet. Your python virtual environment should be set up in the root directory. We'll create the client directory later when we scaffold our React app using Vite.

Setting Up the Backend with Flask and SQLAlchemy

Flask, a micro web framework for Python, provides a solid foundation for our backend. To persist and manage data, we'll use SQLAlchemy, a powerful SQL toolkit and Object-Relational Mapping (ORM) library.

Install Flask and SQLAlchemy:

>pipenv install
...
>pipenv shell
...
>cd server
>pip install Flask SQLAlchemy
...
Enter fullscreen mode Exit fullscreen mode

Create a Flask App:
Create an app.py file in your server folder. This will hold your backend logic, communicating with your database and serving data to your front end.

# app.py
from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

if __name__ == '__main__':
    app.run(debug=True)
Enter fullscreen mode Exit fullscreen mode

Initialize SQLAlchemy:
Create a file called models.py. This will hold the code that builds your database.

# models.py
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100), nullable=False)
    content = db.Column(db.Text, nullable=False)
Enter fullscreen mode Exit fullscreen mode

Frontend Setup with React and Vite

Vite is a next-generation frontend build tool that we'll use to set up our React application.

Create a Vite App:

>cd ..
>npm create vite client --template react
>cd client
Enter fullscreen mode Exit fullscreen mode

Install Dependencies:

>npm install
Enter fullscreen mode Exit fullscreen mode

Connecting the Frontend and Backend

Now that we have our backend and frontend set up, let's connect them to ensure smooth communication between the two.

CORS Handling in Flask:
Cross Origin Resource Scripting, or CORS, prevents unauthorized access to your back end and database. You'll need to configure it to allow your front end to access your back end.

Install the flask-cors extension to handle Cross-Origin Resource Sharing (CORS):
Make sure you're in the root directory and run

>pip install Flask-CORS
Enter fullscreen mode Exit fullscreen mode

Update app.py to include CORS:

#app.py
from flask_cors import CORS
CORS(app)
Enter fullscreen mode Exit fullscreen mode

Fetching Data in React:

Fetching data from the front end is relatively straightforward, but can be made simpler with libraries like axios. Personally, I don't mind vanilla React fetches, so let's look at one of those.

//app.jsx
import React, { useEffect, useState } from 'react';
const App = () => {
  const [data, setData] = useState(null);
  const fetchData = async () => {
  try {
    const response = await fetch(/*url*/);
    const theData = await response.json();
    setData(theData);
  catch (e) {
    console.log(e)
  }
Enter fullscreen mode Exit fullscreen mode

Database Integration with Flask and SQLAlchemy

Now, let's integrate the SQLAlchemy models with Flask to perform CRUD operations.

Create a Database and Migrate:
'Migration' is the term given to creating and changing a database's schema, that is its table and column setup.

flask db init
flask db migrate -m "Initial migration"
flask db upgrade
Enter fullscreen mode Exit fullscreen mode

Define API Endpoints in Flask:

This code will define endpoints in vanilla flask/SQLAlchemy, though the process can be made more pythonic with another plugin called flask-restfull.

# app.py
from flask import jsonify, request

@app.route('/api/posts', methods=['GET'])
def get_posts():
    posts = Post.query.all()
    return jsonify([post.serialize() for post in posts])

@app.route('/api/posts', methods=['POST'])
def create_post():
    data = request.json
    new_post = Post(title=data['title'], content=data['content'])
    db.session.add(new_post)
    db.session.commit()
    return jsonify(new_post.serialize()), 201
Enter fullscreen mode Exit fullscreen mode

Conclusion

Building a full stack app involves seamlessly integrating multiple technologies. Flask, SQLAlchemy, React, and Vite come together to create a robust and efficient application. As you continue to develop, explore additional features such as authentication, state management, and deployment, you will find that you have your own takes and preferences on this process, as the one outlined here is very barebones.

Now that you have a foundational understanding, feel free to dive deeper into each technology to unlock their full potential. Happy coding!

Top comments (0)