Frontend and Backend Development Lesson Notes
Introduction
Frontend and backend are two essential components of a web application. The frontend is the part of the application that interacts with the user, whereas the backend is the part that handles the logic and data processing behind the scenes.
The frontend, also known as the client-side, typically consists of HTML, CSS, and JavaScript code that runs in the user's web browser. The frontend handles the user interface, page layout, and overall look of the application. It also handles user interactions, such as submitting forms, clicking buttons, and navigating between pages.
On the other hand, the backend, also known as the server-side, typically consists of a server, a database, and, in our case, APIs. The backend handles the processing and storage of data, manages user authentication and authorization, and handles business logic and rules. The backend also communicates with the frontend, providing the necessary data to render the user interface and processing user inputs.
Backend
In our class we mainly use Python and SQL/JSON to create APIs and databases. Here is a simple example of creating a SQL database and using CRUD as well.
What is CRUD
-
C: The 'C' stands for create, meaning to create a new entry in a database. In this case, creating a new entry about a certain movie or TV show.
-
R: Read, or to retrieve data from the database. In this case it is selecting the movie/TV shwo that you choose to display.
-
U: Update, or changing an existing entry in the database. In this case it is selecting the preexisting movie/TV show and changing the values to match what you want.
-
D: Delete, or removing data from the database. In this case it is selecting the preexisting movie/TV show and removing the entry from the database.
Films API
This API is intended to be used as a list of movies and TV shows that a person has watched. It includes attributes for the Film name(key), the year released, the language, the number of episodes, A list of the number of episodes(using pickletype), and a youtube url for the trailer. The CRUD works as follows: Create: Enter the above mentioned attributes Read: Returns all of the films and their attributes Update: Takes in new episodes watched, and a list of their names, and adds them to their respective attibutes Delete: Option for deleting every film, also takes in a name to delete that film if it exists
from flask import Flask
import sqlite3
app = Flask(__name__)
# Connect to the SQLite database using SQLite3
conn = sqlite3.connect('films.db')
# Create a cursor object to execute SQL commands
cursor = conn.cursor()
# Create a table in the database
cursor.execute('''CREATE TABLE movies
(id INTEGER PRIMARY KEY, title TEXT, year INTEGER, epcount INTEGER, language TEXT, trailer TEXT, eplist TEXT)''')
# Commit the changes to the database and close the connection
conn.commit()
conn.close()
import sqlite3
def create():
# Ask the user for movie details
title = input("Enter the movie/tv show title: ")
year = input("Enter the movie/tv show release year: ")
epcount = input("Enter the movie/tv show epcount: ")
language = input("Enter the movie/tv show language: ")
eplist = input("Enter the movie/tv show episode names: ")
trailer = input("Enter the link movie/tv show trailer: ")
# Connect to the database and create a cursor to execute SQL commands
database = 'films.db'
connection = sqlite3.connect(database)
cursor = connection.cursor()
try:
# Execute SQL to insert record into db
cursor.execute("INSERT INTO movies (title, year, epcount, language, eplist, trailer) VALUES (?, ?, ?, ?, ?, ?)", (title, year, epcount, language, eplist, trailer))
# Commit the changes
connection.commit()
print(f"{title} has been added to the list of movies.")
except sqlite3.Error as error:
print("Error while inserting record:", error)
# Close cursor and connection
cursor.close()
connection.close()
create()
def read(id):
# Connect to the database and create a cursor to execute SQL commands
database = 'films.db'
connection = sqlite3.connect(database)
cursor = connection.cursor()
# Execute SQL to select a record from db by id
cursor.execute("SELECT * FROM movies WHERE id=?", (id,))
# Fetch the record from the cursor
movie = cursor.fetchone()
# If movie exists, print its details, else print message
if movie:
print(f"{movie[0]}. {movie[1]}, {movie[2]}, {movie[3]}, {movie[4]}, {movie[5]}, {movie[6]}")
else:
print("Movie not found.")
# Close cursor and connection
cursor.close()
connection.close()
read(id=1)
def update(id):
# Connect to the database and create a cursor to execute SQL commands
database = 'films.db'
connection = sqlite3.connect(database)
cursor = connection.cursor()
# Ask the user for movie details to update
title = input("Enter the updated movie/tv show title: ")
year = input("Enter the updated movie/tv show release year: ")
epcount = input("Enter the updated movie/tv show epcount: ")
language = input("Enter the updated movie/tv show language: ")
eplist = input("Enter the updated movie/tv show episode names: ")
trailer = input("Enter the updated link movie/tv show trailer: ")
try:
# Execute SQL to update the record in db
cursor.execute("UPDATE movies SET title=?, year=?, epcount=?, language=?, eplist=?, trailer=? WHERE id=?", (title, year, epcount, language, eplist, trailer, id))
# Commit the changes
connection.commit()
print("Movie updated successfully.")
except sqlite3.Error as error:
print("Error while updating record:", error)
# Close cursor and connection
cursor.close()
connection.close()
update(id=1)
def delete(id):
# Connect to the database and create a cursor to execute SQL commands
database = 'films.db'
connection = sqlite3.connect(database)
cursor = connection.cursor()
try:
# Execute SQL to delete the record from db by id
cursor.execute("DELETE FROM movies WHERE id=?", (id,))
# Commit the changes
connection.commit()
print("Movie deleted successfully.")
except sqlite3.Error as error:
print("Error while deleting record:", error)
# Close cursor and connection
cursor.close()
connection.close()
delete(id=2)
Fetching
Overview
- Involves retrieving data from a server or database
- Can use different HTTP methods, such as GET, POST, PUT, and DELETE, to perform different types of operations on the server.
- Fetching can be done through a variety of ways including AJAX, XHR, and Axios
- In APCSP we tend to use the Fetch API over anything else
- Fetching involves sending a request to a server using a URL (Uniform Resource Locator), which identifies the location of the resource being requested.
- Can receive data in various formats, including JSON
- JSON data can be parsed into objects and arrays in JavaScript, making it easy to work with and manipulate in the frontend
import requests
url = "https://moviesdatabase.p.rapidapi.com/titles"
headers = {
"content-type": "application/octet-stream",
"X-RapidAPI-Key": "8401db6433msh3a46dd5bf23ad2ep19a280jsn48536a994246",
"X-RapidAPI-Host": "moviesdatabase.p.rapidapi.com"
}
response = requests.get(url, headers=headers)
print(response.json())
This is a functional fetch of a movies API from Rapid API, but the data isn't very readable. Below is an example of using Pandas to format the key values as a dataframe.
I added an isEpisode
column
import requests
import pandas as pd
url = "https://moviesdatabase.p.rapidapi.com/titles"
headers = {
"content-type": "application/octet-stream",
"X-RapidAPI-Key": "8401db6433msh3a46dd5bf23ad2ep19a280jsn48536a994246",
"X-RapidAPI-Host": "moviesdatabase.p.rapidapi.com"
}
response = requests.get(url, headers=headers)
data = response.json()
# Create an empty DataFrame
df = pd.DataFrame()
# Extract the required information and store it in a list of dictionaries
results = data["results"]
entries = []
for result in results:
entry = {
"id": result["id"],
"title": result["titleText"]["text"],
"release_year": result["releaseYear"]["year"],
}
entries.append(entry)
# Convert the list of dictionaries into a DataFrame
df = pd.DataFrame(entries)
# ADD YOUR OWN COLUMN TO THE DATAFRAME
results = data["results"]
entries = []
for result in results:
entry = {
"id": result["id"],
"title": result["titleText"]["text"],
"release_year": result["releaseYear"]["year"],
"isEpisode": result["titleType"]["isEpisode"]
}
entries.append(entry)
# Convert the list of dictionaries into a DataFrame
df = pd.DataFrame(entries)
print(df)
Using Pandas to format a request obtained from a 3rd Party API makes it much easier to read and you can select what you want to display as well. Pandas makes it easy to access data that you feel is important.
Write notes below
-
CRUD: Create, read, update, and delete Used for processing and accessing information from the database
-
Frontend, backend example: Movies
- Frontend
- Takes in a Youtube URL, uses string manipulation to convert it into an embed.
- Uses fetch request to output movie information onto a table
- Frontend
-
Fetching uses HTTP methods (GET, POST, etc.)
- Create a completely unique API with all 4 CRUD features (Create, Read, Update, Delete)
- Create a Fetch API request for your corresponding API
- Attempt a complete website on GitHub Pages including HTML
class _ShowClassReview(Resource):
def get(self):
#original code commented out because only searched for one class review per user
#(code below searches for all class reviews, even if one user posted many)
#users = User.query.first()
# json_ready = [user.showClassReview() for user in users]
#json_ready = getClassReview()
reviewList = []
#get all class reviews
classReview = ClassReview.query.all()
#get an individual class review based on id, then add to reviewList
for i in range (1, len(classReview) + 1):
review = getClassReview(ClassReview.query.filter_by(id=i).first())
reviewList.append(review)
#print("FOR LOOP: " + str(ClassReview.query.filter_by(id=i).first()))
#print out reviewlist in json format
return jsonify(reviewList)
#return jsonify(json_ready)
class _UpdateClassReview(Resource):
def post(self):
body = request.get_json()
username = body.get('username')
className = body.get('className')
difficulty = int(body.get('difficulty'))
hoursOfHw = int(body.get('hoursOfHw'))
daysBtwTest = int(body.get('daysBtwTest'))
memorizationLevel = int(body.get('memorizationLevel'))
comments = body.get('comments')
#error checking
if difficulty < 0:
return {'message': f'Invalid number'}, 210
if hoursOfHw < 0:
return {'message': f'Invalid number'}, 210
if daysBtwTest < 0:
return {'message': f'Invalid number'}, 210
if memorizationLevel < 0:
return {'message': f'Invalid number'}, 210
#search for review based on username and classname
user = classReview_obj_by_username(username, className)
if user:
user.update(className, difficulty, hoursOfHw, daysBtwTest, memorizationLevel, comments)
else:
return {'message': f"unable to find class review entries of user '{username}'"}, 210
return user.read()
class _DeleteClassReview(Resource):
def post(self):
body = request.get_json()
username = body.get('username')
className = body.get('className')
#search for review to delete based on username and classname
deleteClass = classReview_obj_by_username(username, className)
print(deleteClass)
if deleteClass:
#NO NEED TO PASS CLASS AS ARGUMENT BECAUSE METHOD DEFAULT
#TAKES IT IN AS self
deleteClass.delete()
else:
return {'message': f"unable to find GPA entries of user '{username}'"}, 210
return deleteClass.read()
class _CreateClassReview(Resource):
def post(self):
''' Read data for json body '''
body = request.get_json()
username = body.get('username')
className = body.get('className')
difficulty = body.get('difficulty')
hoursOfHw = body.get('hoursOfHw')
daysBtwTest = body.get('daysBtwTest')
memorizationLevel = body.get('memorizationLevel')
comments = body.get('comments')
if int(difficulty) < 0:
return {'message': f'Invalid number'}, 210
if int(hoursOfHw) < 0:
return {'message': f'Invalid number'}, 210
if int(daysBtwTest) < 0:
return {'message': f'Invalid number'}, 210
if int(memorizationLevel) < 0:
return {'message': f'Invalid number'}, 210
id = findId(username)
#create a review object based on user's input
review = ClassReview(id=id, className=className, difficulty=difficulty, hoursOfHw=hoursOfHw, daysBtwTest=daysBtwTest, memorizationLevel=memorizationLevel, comments=comments)
#I HAVE TO CHANGE THIS VARIABLE NAME LOL
reviews = review.create()
if reviews:
return jsonify(reviews.read())
# failure returns error
return {'message': f'Processed {username}, either a format error or duplicate'}, 210
fetch("https://seal.nighthawkcodingsociety.com/api/users/classreview")
.then(response => {
response.json().then(data => {
console.log(data);
for (const row of data) {
if (classInput.toUpperCase() == row.className.toUpperCase()) {
const tr = document.createElement("tr");
const className = document.createElement("td");
className.innerHTML = row.className;
const daysBtwTest= document.createElement("td");
daysBtwTest.innerHTML = row.daysBtwTest;
const difficulty= document.createElement("td");
difficulty.innerHTML = row.difficulty;
const hoursOfHw= document.createElement("td");
hoursOfHw.innerHTML = row.hoursOfHw;
const memorizationLevel = document.createElement("td");
memorizationLevel.innerHTML = row.memorizationLevel;
const comments = document.createElement("td");
comments.innerHTML = row.comments;
tr.appendChild(className);
tr.appendChild(daysBtwTest);
tr.appendChild(difficulty);
tr.appendChild(hoursOfHw);
tr.appendChild(memorizationLevel);
tr.appendChild(comments);
document.getElementById("reviews").appendChild(tr);
}
}
})
}
)