Unable to Retrieve Data from RapidAPI in Flutter Application

I am trying to fetch data for my Flutter application. While retrieving data from this endpoint works- https://jsonplaceholder.typicode.com/albums, I am unable to get data when utilizing RapidAPI. I’m uncertain if the issue lies with the server connection.

Here’s my code snippet:

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

Future<List<RecipeData>> loadRecipes() async {
  var endpoint = Uri.https('yummly2.p.rapidapi.com', '/feeds/list',
      {"limit": "18", "start": "0", "tag": "list.recipe.popular"});

  final response = await http.get(endpoint, headers: {
    "x-rapidapi-key": "my_api_key",
    "x-rapidapi-host": "yummly2.p.rapidapi.com",
    "useQueryString": "true"
  });

  if (response.statusCode == 200) {
    List jsonResponse = json.decode(response.body);
    return jsonResponse.map((item) => RecipeData.fromJson(item)).toList();
  } else {
    throw Exception('Error fetching recipes');
  }
}

class RecipeData {
  final String title;

  RecipeData({ required this.title });

  factory RecipeData.fromJson(Map<String, dynamic> json) {
    return RecipeData(title: json['name']);
  }
}

It seems like your issue might be related to the way you’re handling the JSON response. Ensure that the JSON structure you’re expecting matches the actual response. The endpoint you’re trying to access might not be returning a list directly. Instead, it could be an object containing the list.

Try logging response.body to see the exact structure, then adjust your RecipeData.fromJson() method accordingly. The json.decode(response.body) sometimes needs to be accessed with keys to retrieve the list. Moreover, ensure that your headers and API key are correct and your account has permissions to access the endpoint.

Hey harry! You might want to also check if you’re hitting a rate limit on RapidAPI. Even if ur code is good, exceeding the limit can block responses. Try hitting the API with a different key or tweak the limit settings if possible. Also, verify ur subscription level.