API Gradio Spaces error API request failed: 404 {"detail":"Not Found"}

Hi everyone, I called the correct api link but it doesn’t work even though I have the token
here logs


SvelteKitError: POST method not allowed. No actions exist for this page
    at handle_action_json_request (file:///usr/local/lib/python3.10/site-packages/gradio/templates/node/build/server/index.js:926:30)
    at render_page (file:///usr/local/lib/python3.10/site-packages/gradio/templates/node/build/server/index.js:2577:12)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async resolve2 (file:///usr/local/lib/python3.10/site-packages/gradio/templates/node/build/server/index.js:3705:24)
    at async respond (file:///usr/local/lib/python3.10/site-packages/gradio/templates/node/build/server/index.js:3596:22)
    at async Array.ssr (file:///usr/local/lib/python3.10/site-packages/gradio/templates/node/build/handler.js:1261:3) {
  status: 405,
  text: 'Method Not Allowed'
}

client nextjs

const response = await fetch(
      "https://trinhminhhieu-hiussl.hf.space/api/predict",
      {
        method: "POST",
        headers: {
          Authorization: `Bearer ${process.env.HF_TOKEN}`,
          "Content-Type": "application/json",
          Accept: "application/json",
        },
        body: arrayBuffer,
      }
    );
1 Like

status: 405,
text: ‘Method Not Allowed’

405 errors are very rare. 404 errors are common, though…

Hello here error 404


Response {
  [Symbol(realm)]: { settingsObject: {} },
  [Symbol(state)]: {
  aborted: false,
  rangeRequested: false,
  timingAllowPassed: false,
  requestIncludesCredentials: false,
  type: 'default',
  status: 404,
  timingInfo: null,
  cacheState: '',
  statusText: 'Not Found',
  headersList: HeadersList {
  [Symbol(headers map)]: Map(12) {
  'access-control-allow-credentials' => 'true',
  'connection' => 'keep-alive',
  'content-length' => '22',
  'content-type' => 'application/json',
  'date' => 'Sun, 23 Mar 2025 15:46:57 GMT',
  'link' => '<https://huggingface.co/spaces/trinhminhhieu/bgnbl>;rel="canonical"', 
  'server' => 'uvicorn',
  'vary' => 'origin, access-control-request-method, access-control-request-headers', 
  'x-proxied-host' => 'http://10.106.9.151',
  'x-proxied-path' => '/run/predict',
},
  [Symbol(headers map sorted)]: null
},
  urlList: [],
  body: {
  stream: <ref *1> ReadableStream {
  _state: 'readable',
  _reader: undefined,
  _storedError: undefined,
  _disturbed: false,
  _readableStreamController: ReadableStreamDefaultController {
  _controlledReadableStream: [Circular *1],
  _queue: S {
  _cursor: 0,
  _size: 0,
  _front: { _elements: [], _next: undefined },
  _back: { _elements: [], _next: undefined }
},
  _queueTotalSize: 0,
  _started: true,
  _closeRequested: false,
  _pullAgain: false,
  _pulling: false,
  _strategySizeAlgorithm: [Function],
  _strategyHWM: 0,
  _pullAlgorithm: [Function],
  _cancelAlgorithm: [Function]
}
},
  source: null,
  length: null
}
},
  [Symbol(headers)]: Headers {
  [Symbol(headers list)]: HeadersList {
  [Symbol(headers map)]: Map(12) {
  'access-control-allow-credentials' => 'true',
  'connection' => 'keep-alive',
  'content-length' => '22',
  'content-type' => 'application/json',
  'date' => 'Sun, 23 Mar 2025 15:46:57 GMT',
  'link' => '<https://huggingface.co/spaces/trinhminhhieu/bgnbl>;rel="canonical"', 
  'server' => 'uvicorn',
  'vary' => 'origin, access-control-request-method, access-control-request-headers', 
  'x-proxied-host' => 'http://10.106.9.151',
  'x-proxied-path' => '/run/predict',

},
  [Symbol(headers map sorted)]: null
},
  [Symbol(guard)]: 'response',
  [Symbol(realm)]: { settingsObject: {} }
}
}
Error: API request failed: 404 {"detail":"Not Found"}

here code nextjs api for cloudflare

/ /api/upload.js
export const runtime = "edge";

export default async function handler(req) {
  // if (req.method !== "POST") {
  //   return new Response(JSON.stringify({ error: "Method Not Allowed" }), {
  //     status: 405,
  //     headers: { "Content-Type": "application/json" },
  //   });
  // }

  try {
    // Get form data
    const formData = await req.formData();
    const imageFile = formData.get("image");

    if (!imageFile) {
      return new Response(JSON.stringify({ error: "No file uploaded" }), {
        status: 400,
        headers: { "Content-Type": "application/json" },
      });
    }

    // Convert the File object to ArrayBuffer
    const arrayBuffer = await imageFile.arrayBuffer();

    // Send to HF Space API
    const response = await fetch(
      "https://trinhminhhieu-bgnbl.hf.space/run/predict",
      {
        method: "POST",
        headers: {
          Authorization: `Bearer ${process.env.HF_TOKEN}`,
          "Content-Type": "application/json",
          Accept: "application/json",
        },
        body: arrayBuffer,
      }
    );

    console.log(response);
    if (!response.ok) {
      const errorText = await response.text();
      throw new Error(`API request failed: ${response.status} ${errorText}`);
    }

    const result = await response.json();
    console.log("result", result);

    if (result.error) {
      throw new Error(result.error);
    }

    return new Response(
      JSON.stringify({
        processedImageUrl:
          result.data && result.data[0] ? result.data[0].url : result.url,
      }),
      {
        status: 200,
        headers: { "Content-Type": "application/json" },
      }
    );
  } catch (error) {
    console.error("Error:", error.message);
    return new Response(
      JSON.stringify({
        error: "Failed to process image",
        details: error.message,
      }),
      {
        status: 500,
        headers: { "Content-Type": "application/json" },
      }
    );
  }
}

app.py

with gr.Blocks() as demo:
    gr.Markdown("Background Removal ")
    gr.Markdown("Upload an image to remove the background.")

    with gr.Row():
        input_image = gr.Image(type="pil", label="Upload Image")
        output_image = gr.Image(type="pil", label="Output Image")

    btn = gr.Button("Remove Background")

    btn.click(remove_bg, inputs=input_image, outputs=output_image, concurrency_limit=None)


# demo.queue()
server = demo.launch(share=True)
1 Like

Same here…

HF_TOKEN = "hf_my_pro_token"
import base64
import requests
response = requests.get("https://raw.githubusercontent.com/gradio-app/gradio/main/test/test_files/bus.png")
buffer = base64.b64encode(response.content)
headers = {'Authorization': f'Bearer {HF_TOKEN}', 'Content-Type': 'application/json'}
response = requests.post('https://john6666-gradio-server-test.hf.space/api/predict', headers=headers, data=buffer)
print(response.content)
# <Response [404]> # Gradio 5.22.0
# <Response [422]> # Gradio 4.44.0
1 Like

Have you found a solution? Nextjs uses API with @gradio/client it works fine but cloudflare doesn’t support nodejs runtime, vercel the 10 second limit is not enough

1 Like

No. Requests for private spaces have often failed in the past. The Gradio client is an exception to this.

I spent 2 days still can’t find the solution :))

1 Like

i been trying for over three weeks

but HF keeps telling me they’ve fixed it

so

sure glad im not paying for this foolery

now, likely never ever would even consider it

id rather pay for a bag of ice and throw it onto the asphalt

1 Like

The output isn’t perfect, but it does respond, so maybe it’s fixed.

HF_TOKEN = "hf_my_pro_token"
import base64
import requests
response = requests.get("https://raw.githubusercontent.com/gradio-app/gradio/main/test/test_files/bus.png")
buffer = base64.b64encode(response.content)
headers = {'Authorization': f'Bearer {HF_TOKEN}', 'Content-Type': 'application/json'}
response = requests.post('https://john6666-gradio-server-test.hf.space/api/predict', headers=headers, data=buffer)
print(response.content)
# :[{"type":"json_invalid","loc":["body",0],"msg":"JSON decode error","input":{},"ctx":{"error":"Expecting value"}}]}'