First Fullstack App
Published: 2023-12-22 13:15:18

## 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:**

```bash
>pipenv install
...
>pipenv shell
...
>cd server
>pip install Flask SQLAlchemy
...
```
**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.

```python
# 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)
```
**Initialize SQLAlchemy:**
Create a file called models.py. This will hold the code that builds your database.

```python
# 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)
```
### 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:


```bash
>cd ..
>npm create vite client --template react
>cd client
```
Install Dependencies:

```bash
>npm install
```

## 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

```bash
>pip install Flask-CORS
```

Update app.py to include CORS:

```python
#app.py
from flask_cors import CORS
CORS(app)
```

### 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.

```jsx
//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)
  }
```

## 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.

```bash
flask db init
flask db migrate -m "Initial migration"
flask db upgrade
```
### 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.
```python
# 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
```
## 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!