DEV Community

Plug panther
Plug panther

Posted on

Introduction to Flask Package for Building APIs for React

Introduction to Flask Package for Building APIs for React

Flask is a lightweight WSGI web application framework in Python. It is designed with simplicity and flexibility in mind, making it an excellent choice for creating APIs that can be consumed by front-end applications, such as those built with React. In this blog post, we will go through the basics of setting up a Flask API and how to interact with it using a React front-end.

Setting Up Flask

First, you need to install Flask. You can do this using pip:

pip install Flask
Enter fullscreen mode Exit fullscreen mode

Next, create a new file called app.py and set up your basic Flask application:

from flask import Flask, jsonify, request

app = Flask(__name__)

@app.route('/')
def home():
    return "Welcome to the Flask API!"

if __name__ == '__main__':
    app.run(debug=True)
Enter fullscreen mode Exit fullscreen mode

Running this script will start a local development server. You can access it by navigating to http://127.0.0.1:5000/ in your web browser.

Creating API Endpoints

Let's create a simple API that allows us to manage a list of items. We'll start by defining a route to get all items and another to add a new item.

items = []

@app.route('/api/items', methods=['GET'])
def get_items():
    return jsonify(items)

@app.route('/api/items', methods=['POST'])
def add_item():
    item = request.json.get('item')
    items.append(item)
    return jsonify(item), 201
Enter fullscreen mode Exit fullscreen mode

With these routes, you can now get and post items to your API.

Setting Up React

Next, let's set up a basic React application to interact with our Flask API. You can create a new React app using Create React App:

npx create-react-app my-app
cd my-app
Enter fullscreen mode Exit fullscreen mode

Inside your React app, create a new component called ItemList.js:

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

const ItemList = () => {
    const [items, setItems] = useState([]);
    const [newItem, setNewItem] = useState('');

    useEffect(() => {
        fetch('/api/items')
            .then(response => response.json())
            .then(data => setItems(data));
    }, []);

    const addItem = () => {
        fetch('/api/items', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ item: newItem }),
        })
            .then(response => response.json())
            .then(item => setItems([...items, item]));
        setNewItem('');
    };

    return (
        <div>
            <h1>Items</h1>
            <ul>
                {items.map((item, index) => (
                    <li key={index}>{item}</li>
                ))}
            </ul>
            <input 
                type="text" 
                value={newItem} 
                onChange={(e) => setNewItem(e.target.value)} 
            />
            <button onClick={addItem}>Add Item</button>
        </div>
    );
};

export default ItemList;
Enter fullscreen mode Exit fullscreen mode

Finally, include this component in your App.js:

import React from 'react';
import './App.css';
import ItemList from './ItemList';

function App() {
  return (
    <div className="App">
      <ItemList />
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Running the Applications

To run your Flask API, execute:

python app.py
Enter fullscreen mode Exit fullscreen mode

And to run your React application, execute:

npm start
Enter fullscreen mode Exit fullscreen mode

Now you can interact with your Flask API through your React front-end. You should be able to add new items and see them listed.

Conclusion

In this blog post, we covered the basics of setting up a Flask API and how to interact with it using a React front-end. Flask's simplicity and flexibility make it an excellent choice for building APIs, and React's component-based architecture makes it easy to create interactive user interfaces. Happy coding!

Top comments (0)