flutterfirebasegoogle-cloud-functions

Why firebase cloud function return 404 Not found and how to fix it?


Seems like I am making API calls, but i get 404 back. I see function calls are added in cloud console function call counter. But i don't see log console.log("function call begin"); What am I doing wrong?


import * as express from "express";
import * as cors from "cors";
const app = express();

app.use(cors({origin: true}));
const corsHandler = cors({origin: true});
app.use(corsHandler);

const API_KEY = "***";
const genAI = new GoogleGenerativeAI(API_KEY);

app.get("/api", async (req, res) => {
  console.log("function call begin");
  const prompt = req.query.prompt as string;

  if (!prompt) {
    res.status(400).send("Prompt query parameter is required");
    return;
  }
  console.log("Will try to generate text:", prompt);
  try {
    const model = genAI.getGenerativeModel({model: "gemini-1.5-flash"});
    const result = await model.generateContent(prompt);
    const response = await result.response;
    const text = await response.text();
    console.log("Generated text:", text);
    res.status(200).send(text);
  } catch (error) {
    console.error(error);
    res.status(500).send("Error generating content");
  }
});

export const api = functions.https.onRequest(app);

Then call it in flutter

final FirebaseFunctions functions = FirebaseFunctions.instance;

  Future<String?> getResponse(String prompt) async {
    try {
      final HttpsCallable callable = functions.httpsCallable('api');
      final response = await callable.call(<String, dynamic>{
        'prompt': prompt,
      });

      return response.data as String?;
    } catch (e) {
      print('Error: $e');
      return null;
    }
  }

I tried to make a call directly but with the same result

Future<String?> getResponse(String prompt) async {
    try {
      // Construct the request body
      final Map<String, String> body = {
        'prompt': prompt,
      };

      // Make the POST request
      final response = await http.post(
        Uri.parse(functionUrl),
        headers: {'Content-Type': 'application/json'},
        body: jsonEncode(body),
      );

      // Check for successful response
      if (response.statusCode == 200) {
        // Return the response body as a string
        return response.body;
      } else {
        print('Error: ${response.statusCode}');
        return null;
      }
    } catch (e) {
      print('Error: $e');
      return null;
    }
  }

Solution

  • You can't realistically use the Firebase callable SDK to invoke endpoints that are not also callable functions defined with onCall (instead of onRequest) as shown in the documentation. Callable functions have their own protocol, which you are not using here. Instead, you should ignore the Firebase client library entirely and just use some other HTTP client library to invoke the function endpoint of your express app.