skip to Main Content

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?

2

Answers


  1. Yes, you should make request from the frontend. The idea is that the client makes a request and the server serves.

    There are some choices available. You could make your own HTTP request. The API is there, so it’s possible. But you’ll probably want to use axios or some derivative of the fetch API. It’s been awhile since I’ve been doing frontend, so I’m not in a position to suggest the best solution. In the old days, I found the package I needed and ran it against npm trends to assert my decision or find alternatives.

    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search