article

Saturday, February 25, 2023

Fastapi React

Fastapi React

Install Fastapi

https://github.com/tiangolo/fastapi

pip install fastapi
C:\fastAPI\react>pip install fastapi
C:\fastAPI\react>pip install "uvicorn[standard]"

Create main.py
react/main.py
 
//react/main.py
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_methods=["*"],
    allow_headers=["*"],
    allow_credentials=True,
    allow_origins=["http://localhost:3000"]
)

@app.get('/get_data')
async def get_data():
    return {'body': 'Hello World from python fastapi'}
run the FastAPI app

C:\fastAPI\react>uvicorn main:app --reload
with uvicorn using the file_name:app_instance open the link on the browser http://127.0.0.1:8000/
http://127.0.0.1:8000/docs
Create Project
C:\react-js>npx create-react-app myreactdev

Run
C:\react-js\myreactdev> npm start

Install Axios
https://www.npmjs.com/package/axios
C:\react-js\myreactdev>npm install axios --save

C:\react-js\myreactdev\src\App.js
//myreactdev\src\App.js
import axios from "axios";
import { useState, useEffect } from "react";

function App() {
    const [ body, setBody ] = useState('')
    
    useEffect( () => {
        axios
            .get("http://127.0.0.1:8000/get_data")
            .then((response) => {
                const data = response.data
                setBody(data['body'])
            })
            .catch( (e) => {
                // Placeholder
            })
    }, [])

    return (
        <div>
            <p><h1>{body}</h1></p>
        </div>
    );
}

export default App;
Run C:\react-j\myreactdev>npm start

Related Post