Search code examples
reactjsflask-restful

Routing requests with flask + react


I'm currently building flask + react application where flask has a role of restful api. Now if a get request sent to the "/api/user/int:userid", it will be responded with json object containing some information about user.

So, my question is how do I route anyone's request to let's say "/profile/int:userid"? Should I be handling this on the frontend side, which sends a request to the api and if yes, then how do I actually implement it? I meen do I need somehow obtain a request params on the client-side and then send it to the backend with axios or whatever?


Solution

  • first thing to do is to setup a page component in react and pass to it the user id like this :

    <Route path="/profile/:userid" element={<UserProfile />} />

    second thing is in <UserProfile /> you need to grab that userId using useParams hook and send it with the request to flask :

    `import React, { useEffect, useState } from 'react'; import { useParams } from 'react-router-dom'; import axios from 'axios';

    function UserProfile() {
      const { userid } = useParams(); // Extract the 'userid' parameter from the URL
      const [userData, setUserData] = useState(null);
    
      useEffect(() => {
        // Function to fetch user data from the backend API
        const fetchUserData = async () => {
          try {
            const response = await axios.get(`/api/user/${userid}`); // Send GET request to Flask API
            setUserData(response.data); // Store the response data in the state
          } catch (error) {
            console.error("Error fetching user data:", error);
          }
        };
    
        fetchUserData();
      }, [userid]); // This effect runs every time the 'userid' changes
    
      if (!userData) {
        return <div>Loading...</div>;
      }
    
      return (
        <div>
          <h1>User Profile</h1>
          <p>Name: {userData.name}</p>
          <p>Email: {userData.email}</p>
          {/* Render other user info */}
        </div>
      );
    }
    
    export default UserProfile;`
    

    third, this is you should setup the endpoint to accept the userId (with auth):

    `from flask import Flask, jsonify
    
    app = Flask(__name__)
    
    # Example user data (in reality, you would fetch from a database)
    users = {
        1: {"name": "John Doe", "email": "[email protected]"},
        2: {"name": "Jane Smith", "email": "[email protected]"},
    }
    
    @app.route('/api/user/<int:userid>', methods=['GET'])
    def get_user(userid):
        user = users.get(userid)
        if user:
            return jsonify(user)
        else:
            return jsonify({"error": "User not found"}), 404
    
    if __name__ == '__main__':
        app.run(debug=True)`
    

    that's if I get what you want