How to Set Up a Backend Server with Flask for Your Full Stack Application

Devincb93 - Sep 5 - - Dev Community

When building a full stack application, it's essential to understand that these apps have two main components: the frontend (what users see and interact with) and the backend (which handles the logic, database interactions, and communication between the frontend and the server).

In this post, I'll guide you through setting up the backend server using Flask, a lightweight and versatile Python web framework. While we won't cover the entire full stack setup, this will give you a solid foundation for building the backend of your application.

To get started, you'll need to install Flask. You can do this by running the following command in your terminal:

pip install Flask
Enter fullscreen mode Exit fullscreen mode

A well-structured backend makes your application more maintainable and easier for other developers to understand. Here’s a basic structure I like to use:

app.py – The main entry point of your application.
config.py – For storing configuration settings.
models.py – Where your database models live.
seed.py – Optional, but useful for populating your database with initial data.

Let’s break down these files:

The config.py file is where you define the settings for your application. This includes setting up the database and enabling Cross-Origin Resource Sharing (CORS) for communication between your frontend and backend. CORS is crucial when your frontend and backend are hosted on different domains, allowing them to interact securely.

Here’s a basic example of what your config.py might look like:

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///app.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SECRET_KEY'] = 'edikeyted'

account_sid = 'AC23debc44a9e96efddf2d1e91b210f9ec'
auth_token = '7b61474dd955a4b6a31a8ccde84d3bce'
client = Client(account_sid, auth_token)


app.json.compact = False

# Define metadata, instantiate db
metadata = MetaData(naming_convention={
    "fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
})
db = SQLAlchemy(metadata=metadata)
migrate = Migrate(app, db)
db.init_app(app)

# Instantiate REST API
api = Api(app)

# Instantiate CORS
CORS(app, resources={r"/*": {"origins": "*"}}, supports_credentials=True)

Enter fullscreen mode Exit fullscreen mode

The app.py file is where you define the routes (or endpoints) that handle requests from the frontend. For example, if you have a table of dogs in your database and want to retrieve specific dogs based on their breed, you can create an endpoint like this:

class GetDogsByBreed(Resource):
    def get(self, breed):
        dogs = Dogs.query.filter(Dogs.breed == breed).all()
        dogs_dict_list = [dog.to_dict() for dog in dogs]  # Convert to JSON-friendly format
        return dogs_dict_list, 200

api.add_resource(GetDogsByBreed, '/dogs/<string:breed>')

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

In the example above, the GetDogsByBreed class handles GET requests to fetch dogs of a specific breed from the database. It takes the breed as a parameter from the frontend, queries the database for matching records, converts them to a JSON format, and sends the data back to the frontend.

This is just one example of how you can structure your backend with Flask. Once you have this basic setup, you can expand it by adding more routes, integrating authentication, and connecting it to your frontend built with React.

Setting up the backend of a full stack application is a critical step in the development process. By organizing your code, properly configuring your application, and creating efficient endpoints, you’ll be well on your way to building a robust and scalable app. In future posts, you can expand on this by covering how to connect your Flask backend to a React frontend or deploy your full stack application.

Feel free to experiment with this setup and customize it to fit the needs of your specific project. Happy coding!

. . . . . .
Terabox Video Player