Full Stack Software Engineering for Beginners

July 25st, 2023


Integrating Frontend and Backend: Making API Requests from the Client-Side

In this class material, we will learn how to integrate frontend and backend using Python Flask as the backend framework and JavaScript for the frontend. We will create a simple “To-Do List Application” to demonstrate how API requests are made from the client-side to interact with the backend server.

Setting Up the Backend Server (Python Flask)

Create the Flask App

  • Create a new Python file (e.g., app.py) and set up a basic Flask app with routes to handle API requests.

Example app.py:

from flask import Flask, jsonify, request

app = Flask(__name__)

# Sample data (Replace this with your database)
todos = [
    { 'id': 1, 'task': 'Buy groceries', 'done': False },
    { 'id': 2, 'task': 'Clean the house', 'done': True }
]

@app.route('/api/todos', methods=['GET'])
def get_todos():
    return jsonify(todos)

@app.route('/api/todos', methods=['POST'])
def add_todo():
    new_todo = request.json
    new_todo['id'] = len(todos) + 1
    todos.append(new_todo)
    return jsonify(new_todo), 201
  • In the terminal, run the Flask server using the following command:
python3 app.py

Setting Up the Frontend (JavaScript)

Step 1: Create HTML and CSS Files

  • Create an index.html file to build the user interface of the To-Do List Application.

  • Create a separate styles.css file to style the application.

Step 2: Create JavaScript Code

  • Add a script tag in the HTML file to include your JavaScript code.

Example scripts.js:

const todosContainer = document.getElementById('todos-container');
const apiUrl = '/api/todos';

function displayTodos() {
    fetch(apiUrl)
        .then(response => response.json())
        .then(todos => {
            todos.forEach(todo => {
                const todoItem = document.createElement('div');
                todoItem.innerHTML = `<input type="checkbox" ${todo.done ? 'checked' : ''}> ${todo.task}`;
                todosContainer.appendChild(todoItem);
            });
        })
        .catch(error => console.error('Error fetching todos:', error));
}

function addTodo() {
    const newTodo = { task: 'New Task', done: false };
    fetch(apiUrl, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(newTodo)
    })
    .then(response => response.json())
    .then(todo => {
        const todoItem = document.createElement('div');
        todoItem.innerHTML = `<input type="checkbox" ${todo.done ? 'checked' : ''}> ${todo.task}`;
        todosContainer.appendChild(todoItem);
    })
    .catch(error => console.error('Error adding todo:', error));
}

displayTodos();

Promise API

The Promise API is a feature in JavaScript that allows you to work with asynchronous operations more easily and efficiently. It provides a way to handle the result (fulfillment) or error (rejection) of an asynchronous operation in a more structured and readable manner.

A Promise is an object that represents a value that may not be available yet but will be resolved or rejected at some point in the future. The Promise can be in one of three states:

Pending: The initial state when the Promise is created, and the asynchronous operation is still ongoing.

Fulfilled (Resolved): The state when the asynchronous operation is successful, and the Promise has a result.

Rejected: The state when the asynchronous operation encounters an error, and the Promise has a reason for the failure.

Pop Quizzes

Questions

  1. Question 1: How can you add a new task to the To-Do List Application from the frontend?

  2. Question 2: What does the jsonify function do in the Python Flask backend?

  3. Question 3: How can you display the list of todos on the frontend?

  4. Question 4: How can you mark a todo as completed on the frontend?

  5. Question 5: What HTTP status code is returned when a new todo is successfully added?

Answers

  1. By making a POST request to the backend API endpoint.
  2. The jsonify function converts a Python dictionary into a JSON response that can be sent to the client.
  3. By making a GET request to the /api/todos endpoint and dynamically adding the todos to the DOM.
  4. By adding an event listener to the checkbox and making a PUT request to update the todo status in the backend.
  5. HTTP status code 201 (Created).

Hands-on assignments:

Choose one topic from the following options. Try building the front-end and back-end for the task.

  1. Contact Book Application: Build a web application that allows users to add, edit, and delete contacts. Use frontend technologies like HTML, CSS, and JavaScript to create the user interface, and use Python Flask as the backend to handle API requests for CRUD operations on the contact data.

  2. E-commerce Product Catalog: Create a product catalog web application where users can view a list of products, search for specific products, and view product details. Implement API endpoints to handle product retrieval from the backend and use JavaScript to fetch and display the data on the frontend.

  3. Task Management System: Develop a task management system that enables users to add tasks, set due dates, mark tasks as completed, and delete tasks. Utilize a database to store task data and use API requests to interact with the backend for managing tasks.

  4. Weather Forecast Application: Design a weather forecast application that fetches weather data from a public API and displays current weather information and forecasts for different locations. Use JavaScript to handle API requests to the backend and present the data in an easily understandable format on the frontend.

  5. Online Voting Platform: Create an online voting platform where users can vote for various topics or polls. Implement API endpoints to record votes on the backend and use JavaScript to handle user interactions on the frontend. Ensure that users can view real-time vote counts and results.