Lab 2.3 - Connect the website to the REST API

Kubernetes dive-in workshop


DATE:
Friday, March 29, 2024

Objective

The objective is to connect the website to the REST API. At the end of this step, the website should display the list of students from the REST API.

Instructions

Step 1

We edit the file pages/index.js and replace the content with the following code:

'use client'; import { useEffect, useState } from 'react'; export default function Home() { const [students, setStudents] = useState([ { name: 'Loading...', email: 'Loading...', }, ]); useEffect(() => { fetch('http://localhost:5000/', { method: 'GET', headers: { 'Content-Type': 'application/json', }, }) .then((res) => res.json()) .then((students) => { if (Array.isArray(students.students)) { console.log(students); setStudents(students.students); } }) .catch((error) => { console.log(error); }); }, []); return ( <div className="relative overflow-x-auto"> <table className="w-full text-left text-sm text-gray-500 dark:text-gray-400 rtl:text-right"> <thead className="bg-gray-50 text-xs uppercase text-gray-700 dark:bg-gray-700 dark:text-gray-400"> <tr> <th scope="col" className="px-6 py-3"> Student </th> <th scope="col" className="px-6 py-3"> Email </th> </tr> </thead> <tbody> {students.map((student, index) => ( <tr className="border-b bg-white dark:border-gray-700 dark:bg-gray-800" key={index}> <th scope="row" className="whitespace-nowrap px-6 py-4 font-medium text-gray-900 dark:text-white"> {student.name} </th> <td className="px-6 py-4">{student.email}</td> </tr> ))} </tbody> </table> </div> ); }

Step 2

We configure the CORS policy in the FastAPI application.

from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware app = FastAPI() app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["GET"], allow_headers=["*"], ) @app.get("/") def read_root(): return { "students": [ { "name": "Mehrshad Lotfi", "email": "mehrshad@optiop.org" }, { "name": "Reza Mohammadi", "email": "reza@optiop.org" } ] }