Home > OS >  FLASK request.json not working with React payload
FLASK request.json not working with React payload

Time:02-19

I have a flask route that queries my DB for locations and services based on a radius. Testing and working with POSTMAN.

@bp.route('/provider-locations/<int:radius>', methods=['GET'])
def get_locations_from_radius(radius):
    user_latitude = request.json['lat']
    user_longitude = request.json['lng']

    my_obj = {}
    my_obj_container = []

    locations = db_session.query(ProviderLocation).filter(\
    func.acos(func.sin(func.radians(user_latitude)) \
        * func.sin(func.radians(ProviderLocation.latitude))   \
            func.cos(func.radians(user_latitude)) * \
                func.cos(func.radians(ProviderLocation.latitude)) * \
                    func.cos(func.radians(ProviderLocation.longitude) - \
                        (func.radians(user_longitude)))) * 6371 <= radius)

    for location in locations:
        services = db_session.query(ProviderService).select_from(ProviderService).join(\
            ServiceLocationLink).filter(ServiceLocationLink.location_id == location.id).all()
        
        my_obj = provider_location_list_schema.dump(location)
        my_obj['services'] = [provider_service_list_schema.dump(service) for service in services]
        my_obj_container.append(my_obj)

    return jsonify(my_obj_container)

My error comes in trying to pass this req the expected params from my client (React). I keep receiving a 400 response.

export async function getLocationServicesByRadius(radius, user_address) {
    try {
        const body = {
            lat: user_address.lat,
            lng: user_address.lng
        }
        return await awsApiRequest({
            method: 'GET',
            path: `/provider-locations/${radius}`,
            params: {
                body: body
            },
        });
    } catch (err) {
        console.log(err.message)
    }
}
  const fetchLocationServices = async () => {
    const userAddress = {
      lat: 43.829640,
      lng: -79.470310
    }
    const { data, success, errorMessage } = await getLocationServicesByRadius(userDistance, userAddress)
    if (success) {
      console.log('RADIUS =>', data)
    } else {
      console.log(errorMessage)
    }
  }

I must be missing something somewhere but can not figure out why the req is returning 400.

the body from the client looks as so:

{
   lat: 43.82964
   lng: -79.47031
}

CodePudding user response:

In flask request.json is used to access POST request body, for GET requests use request.args.

  • Related