DEV Community

bellagerken
bellagerken

Posted on

How to build a GET Api using Flask

In order to make a GET request in a front end React application from the server, the server needs to be set up in that it sends an object array in JSON format. On the front end, you might see something like this:

function tripList() {
  const [trips, setTrips] = useState([]);

  useEffect(() => {
    fetch("http://localhost:4000/trips")
      .then((r) => r.json())
      .then((trips) => setTrips(trips));
  }, []);

  return (
    <section>
      {trips.map((trip) => (
        <TripItem key={trip.id} trip={trip} />
      ))}
    </section>
  );
}
Enter fullscreen mode Exit fullscreen mode

To set up the back end of the GET request, there are some initializers to be set up first. At the top of an app.py file, you will start with something that looks like this:

from flask import Flask, jsonify, make_response
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate

from models import db, User, Review, Game

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///app.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.json.compact = False

migrate = Migrate(app, db)

db.init_app(app)
Enter fullscreen mode Exit fullscreen mode

Using jsonify allows us to serialize our arguments (lists or dictionaries) as JSON and subsequently returns a response. make_response is what is used to send back the data. To begin setting up the GET request, we can start by settings up an @app.route('/trips') to our list of trips. From there, we want to define a function called def trips. Next, the idea is to grab all of the trips that we have a put them in a list, which we will then jsonify and send the response via make_response. To begin, we want to set up an empty list and set it equal to a variable such as "trips". Next, we will use query to get all of our trips which will look like: Trips.query.all(). However, it's important to serialize each trips in all trips and to resolve that issue we can create a for loop. Within the for loop, the next step is to create the dictionary object for the trip. For example:

for trip in Trips.query.all():
    trip_dict = {
       "date": trip.date,
       "location": trip.location
    }
Enter fullscreen mode Exit fullscreen mode

Next, we want to append these trip_dict's to the empty list that we created. After that, we can create a variable called "response" and set it equal to make_response(jsonify(trips), 200). Lastly within the function we want to return the response! This is how you set up a GET request in Flask. See below for the full code under @app.route.

@app.route('/trips')
def trips():

    trips = []
    for trip in Trip.query.all():
        trip_dict = {
            "date": trip.date,
            "location": trip.location,
        }
        trips.append(trip_dict)

    response = make_response(
        trips,
        200,
        {"Content-Type": "application/json"}
    )

    return response
Enter fullscreen mode Exit fullscreen mode

Top comments (0)