How to receive and send data from an React application to a Flask API?

Asked

Viewed 62 times

0

I am making an app in React and would like to use Flask to save user data in a local database. I was able to make React and flask "run on the same door" and thus enable a connection between them. For this, I followed the following steps (which can be seen in this tutorial):

1st Create App in React

I created the app using npx:

npx create-react-app react-flask-app

2nd Creates API in Flask

mkdir api
cd api
python3 -m venv venv
source venv/bin/activate
(venv) 

Minimum code for example:

import time
from flask import Flask

app = Flask(__name__)

@app.route('/time')
def get_current_time():
    return {'time': time.time()}

3rd Configure package.json

I add the line:

"proxy": "http://localhost:5000"

In the first "dictionary" of the file package.json. This ensures that React will run on the same port as Flask. Finally, on the same file as the key scripts, add:

"start-api": "cd api && venv/bin/flask run --no-debugger"

With these settings - and the two applications running on different terminals -, I can receive API data using fetch in my React application. Example:

import React, { useState, useEffect } from 'react';

function App() {
  const [currentTime, setCurrentTime] = useState(0);

  useEffect(() => {
    fetch('/time').then(res => res.json()).then(data => {
      setCurrentTime(data.time);
    });
  }, []);

  return (
    <div className="App">
      <header className="App-header">

        <p>The current time is {currentTime}.</p>
      </header>
    </div>
  );
}

export default App;

This worked perfectly. However, I don’t know how I do to send data from my React application to the Flask API. Obviously, if the data is within a form, I can use the POST and GET methods to send the data to Flask.

In my case, however, my application generates an array of objects that I would like to send to the API and treat it with python. My array has a face like this:

const users= [
  {
    id: 1,
    name: 'Leanne Graham',
    username: 'Bret',
    email: '[email protected]'
  },
  {
    id: 2,
    name: 'Ervin Howell',
    username: 'Antonette',
    email: '[email protected]'
  },
  {
    id: 3,
    name: 'Clementine Bauch',
    username: 'Samantha',
    email: '[email protected]'
  },
  {
    id: 4,
    name: 'Patricia Lebsack',
    username: 'Karianne',
    email: '[email protected]'
  },
  {
    id: 5,
    name: 'Chelsey Dietrich',
    username: 'Kamren',
    email: '[email protected]'
  },
  {
    id: 6,
    name: 'Mrs. Dennis Schulist',
    username: 'Leopoldo_Corkery',
    email: '[email protected]'
  },
  {
    id: 7,
    name: 'Kurtis Weissnat',
    username: 'Elwyn.Skiles',
    email: '[email protected]'
  },
  {
    id: 8,
    name: 'Nicholas Runolfsdottir V',
    username: 'Maxime_Nienow',
    email: '[email protected]'
  },
  {
    id: 9,
    name: 'Glenna Reichert',
    username: 'Delphine',
    email: '[email protected]'
  },
  {
    id: 10,
    name: 'Clementina DuBuque',
    username: 'Moriah.Stanton',
    email: '[email protected]'
  }
];

In short, I think I’ve figured out how to get data into React from the Flask API and send data from a form. But how do I send an array of objects?

P.S: Maybe it was a little bit abstract why I wanted to pass a list of objects to the API. So here’s a less abstract explanation: my application is a Pomodoro that generates an array with user session information. See the code on Github. The variable I want to send to the Flask API is called userdata.

  • I don’t understand what the problem is. Why don’t you send this array to JSON via POST? You don’t know how to do this using fetch? I confess I don’t understand...

  • I don’t know how to do this using fetch. I actually discovered this function today and had understood that it only served to receive API data (I had even thought to ask which is the opposite of fetch). How do I send data using fetch?

1 answer

0

As suggested in the comments, it is possible to use the same function fetch to send an object to the flask API. This requires adding some parameters to the function:

useEffect(() => {
    const requestOptions = {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({test: "Mensagem no terminal do flask e no console")
    };
        fetch('/home', requestOptions)
        .then(response => response.json())
        .then(data => console.log(data));        
    }, []);

In Flask, it’s used request.json to access the received data, as documentation:

@app.route('/home', methods=['GET', 'POST'])
def post():
    result=request.json
    print(result)
    return result

Browser other questions tagged

You are not signed in. Login or sign up in order to post.