I’m having trouble getting my Flutter app to work with RapidAPI endpoints
My app works perfectly when I fetch data from regular JSON endpoints, but when I try to connect to RapidAPI services, nothing loads. I’m not sure if this is a server connection issue or something wrong with my implementation.
Here’s my current code:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
Future<List<Recipe>> getRecipes() async {
var endpoint = Uri.https('spoonacular-recipe-food-nutrition-v1.p.rapidapi.com', '/recipes/random',
{"number": "20", "limitLicense": "false", "tags": "vegetarian"});
final result = await http.get(
endpoint,
headers: {
"X-RapidAPI-Key": "your_api_key_here",
"X-RapidAPI-Host": "spoonacular-recipe-food-nutrition-v1.p.rapidapi.com",
"Content-Type": "application/json"
}
);
if (result.statusCode == 200) {
List responseData = json.decode(result.body);
return responseData.map((item) => Recipe.fromJson(item)).toList();
} else {
throw Exception('Could not fetch recipes');
}
}
class Recipe {
final String title;
Recipe({required this.title});
factory Recipe.fromJson(Map<String, dynamic> json) {
return Recipe(
title: json['title'],
);
}
}
double-check you’re using your actual API key, not the placeholder “your_api_key_here” text. happens all the time lol. also test the endpoint in postman or curl first to make sure it works outside flutter
Your code has an issue with how you’re handling the Spoonacular API response. The /recipes/random endpoint doesn’t return recipes directly - they’re nested inside a recipes array. You’re trying to decode result.body as a List, but it’s actually a Map with a recipes key.
Here’s the fix:
if (result.statusCode == 200) {
Map<String, dynamic> responseData = json.decode(result.body);
List recipesList = responseData['recipes'];
return recipesList.map((item) => Recipe.fromJson(item)).toList();
}
Also, double-check that your API key is valid and hasn’t expired. I’ve used this API before, and this response structure trips up tons of people.
Check your error handling first - you’re throwing an exception without seeing what the API actually returns when it fails. Add debug prints to catch the real status code and response body. I hit similar issues with RapidAPI endpoints and found they’ll return 403 even with valid keys if you’re rate limited or have subscription problems. Some RapidAPI services also need specific user agent headers or have CORS restrictions. Try adding a User-Agent header - Spoonacular’s API gets picky about requests that look too “automated” without proper headers. Also check if you’re hitting rate limits. RapidAPI free tiers have crazy low request limits per minute, and they’ll just silently fail or throw errors if you go over.