I shipped a deploy late one night, went to bed, and woke up to every image-description call failing. The log was a wall of the same line: You do not have permission to access the File ... or it may not exist. Nothing in the code had changed. I spent the better part of an hour clicking between API key screens, convinced it was a permissions problem, before I noticed that the files/... names stored in my database were two days old.
The short version: files uploaded through the File API are deleted automatically after 48 hours. Store the name and reuse it two days later, and the call will fail at some point that day. That is documented behavior, not a bug. The restart was only the trigger — it made the app re-read old names, and those names happened to be past their window.
The catch is that the same message shows up for reasons that have nothing to do with expiry: a key from a different project, a client created for Vertex AI, or a video handed to the model while it is still processing. The symptoms look alike, the fixes do not. Below I go from checking file state, to narrowing down the error, to choosing how to pass files at all, to structuring code around the window. The limits quoted here come from re-reading the official File input methods and Files API pages in December 2026.
First: read the file's state and expiry with files.get
Before reasoning from the error text, call files.get with the name you saved. A live file returns its state and its scheduled deletion time; a gone file raises. One call tells you whether expiry is the story.
This uses the official Python SDK, google-genai:
# Check whether a saved File name is still usable
import os
from google import genai
from google.genai import errors
client = genai.Client(api_key=os.environ["GEMINI_API_KEY"])
saved_name = "files/abc123def456" # name pulled from your DB (example)
try:
info = client.files.get(name=saved_name)
print("state:", info.state.name) # PROCESSING / ACTIVE / FAILED
print("expires:", info.expiration_time) # scheduled deletion (UTC)
print("uri:", info.uri)
except errors.ClientError as e:
# expired, wrong project, etc.
print("not retrievable:", e.code, e.message)For a live file, the output looks roughly like this:
state: ACTIVE
expires: 2026-12-03 05:12:44.118000+00:00
uri: https://generativelanguage.googleapis.com/v1beta/files/abc123def456I read expiration_time rather than counting 48 hours myself. Once retries and re-uploads enter the picture, a hand-tracked timestamp drifts. I started out storing the upload time and subtracting; every re-upload path I forgot to update became a bug, so the API's own timestamp became the source of truth.
The docs don't say which status code you get for a missing file. Forum reports consistently show 403 PERMISSION_DENIED with the message above, and that is what I saw for expired names too. But as the next section shows, the same 403 has other causes — so decide by whether files.get succeeds, not by the status number.
Troubleshooting table
If files.get fails, or it succeeds but generation still fails, narrow it down here. Working top to bottom, most cases resolve within the first two rows.
| Symptom | Likely cause | How to check | Fix |
|---|---|---|---|
may not exist on a name that worked yesterday | The 48-hour window passed and the file was deleted | files.get fails; compare against your upload records | Re-upload from the original and store the new name |
may not exist right after uploading | Upload and generation use API keys from different projects | Compare which Google Cloud project each key belongs to in AI Studio | Use keys from the same project — files are stored per project |
| Works locally, fails only in production | Production has a different key, or a client created with vertexai=True | Check client initialization and which project the production key came from | The File API belongs to the Gemini API (API key) side. On Vertex AI, pass Cloud Storage URIs directly |
| Video calls fail, then pass after a short wait | The file is still PROCESSING when passed to the model | Look at state from files.get | Poll until ACTIVE before generating |
state is FAILED | The format or contents could not be processed | Check MIME type, extension, and whether the file is corrupt | Fix the format and re-upload |
| Uploads themselves start failing | The project hit its 20 GB storage limit | Count remaining files with files.list | Delete files with files.delete once you are done with them |
The second row is the one that eats an afternoon. If you split keys between development and production, and uploads happen in an admin batch while generation happens on the API server, projects can get crossed without anyone noticing. I suspect that is exactly why the message hedges with "no permission, or it may not exist."
On the third row: a Google staff member answered on the developer forum that the File API is not supported in the Vertex AI SDK. On Vertex AI, the usual path is to pass the gs:// URI of a file in Cloud Storage.
There are four ways to pass a file
The most reliable way to stop fighting the window is to recognize when you don't need the File API at all. As of December 2026, the official docs lay out four methods.
| Method | Good for | Size limit | Persistence |
|---|---|---|---|
| Inline data | Small files used once, real-time requests | 100 MB per request (50 MB for PDFs) | None — sent every time |
| File API upload | Large files, or files reused within a short span | 2 GB per file, 20 GB per project | 48 hours |
| File API Cloud Storage registration | Large files already in Cloud Storage | 2 GB per file, no overall limit | Fetched per request; one registration gives up to 30 days of access |
| External URLs (public or signed) | Files already hosted on the web or in a cloud bucket | 15 MB per file | None — fetched per request |
My rule of thumb: used once, send it inline; reused within 48 hours, upload it; already in the cloud, register it or pass the URL. The only awkward case is "reused, but beyond 48 hours," and the patterns below absorb that.
One more thing worth knowing: you cannot download files you uploaded. The Files API page states this plainly — only model-generated files such as videos can be downloaded. So the File API can't double as a backup, and the original always needs to live somewhere you control.
Pattern 1: send one-off images inline
A screenshot attached to a chat message, answered once and done, is a perfect fit for inline data. Nothing is stored server-side, so nothing can expire.
# Send a small image inline, no File API involved
import os, pathlib
from google import genai
from google.genai import types
client = genai.Client(api_key=os.environ["GEMINI_API_KEY"])
image_bytes = pathlib.Path("photo.jpg").read_bytes()
response = client.models.generate_content(
model="gemini-3.8-flash",
contents=[
types.Part.from_bytes(data=image_bytes, mime_type="image/jpeg"),
"Describe what is in this image.",
],
)
print(response.text)The limit is 100 MB per request, 50 MB for PDFs. An earlier version of this article said 20 MB; the docs have since raised it, so I've corrected that here. Even so, downscaling phone photos before sending makes both the transfer and the response faster — I wrote up the reasoning in why to shrink images with Pillow before sending them.
If older sample code of yours still names gemini-2.5-flash, it's worth updating the model too. Google announced that from December 1, 2026, calls naming gemini-2.5-flash would be routed automatically to gemini-3.5-flash-lite.
Pattern 2: own the original, treat the File name as disposable
For videos and large PDFs that genuinely need the File API, the basic shape is: keep the original in your own storage, and treat the File API name as a copy that disappears after 48 hours. Check it right before use; if it's gone, upload again from the original.
# Reuse the file if it's alive; otherwise re-upload from the original
import os, time, datetime
from google import genai
from google.genai import errors
client = genai.Client(api_key=os.environ["GEMINI_API_KEY"])
MARGIN = datetime.timedelta(hours=2) # don't use names close to expiry
def usable(name: str | None):
if not name:
return None
try:
info = client.files.get(name=name)
except errors.ClientError:
return None # expired, wrong project, etc.
now = datetime.datetime.now(datetime.timezone.utc)
if info.state.name == "ACTIVE" and info.expiration_time - now > MARGIN:
return info
return None
def wait_active(info, timeout_s: int = 300):
start = time.time()
while info.state.name == "PROCESSING":
if time.time() - start > timeout_s:
raise TimeoutError(f"{info.name} never became ACTIVE")
time.sleep(5)
info = client.files.get(name=info.name)
if info.state.name != "ACTIVE":
raise RuntimeError(f"{info.name} state: {info.state.name}")
return info
def get_or_upload(local_path: str, saved_name: str | None):
info = usable(saved_name)
if info:
return info, False
uploaded = client.files.upload(file=local_path)
return wait_active(uploaded), True # True means: store the new name
file, renewed = get_or_upload("video.mp4", saved_name="files/oldname123")
if renewed:
print("store new name:", file.name)
response = client.models.generate_content(
model="gemini-3.8-flash",
contents=[file, "Give me the three main points of this video."],
)
print(response.text)Three details matter here. First, a name with less than two hours left counts as unusable — otherwise a long video job can cross the deadline mid-run. Second, wait out PROCESSING right after upload; that heads off row four of the table. Third, always store the new name after re-uploading. Old names never come back, and if you forget, every call re-uploads and your transfer volume quietly balloons.
For the original, any inexpensive store works: Cloudflare R2, Cloud Storage, S3. I already run my own websites on Cloudflare, so originals live in R2 and only go to the File API at the moment Gemini needs them.
Pattern 3: register files that already live in Cloud Storage
If the originals are already in Cloud Storage, you can register them instead of uploading. Nothing is copied to the Gemini side; the data is fetched per request, and one registration grants up to 30 days of access — no 48-hour window.
The prerequisites: grant the Gemini API service agent read access to the bucket, and build the client from credentials with Cloud Storage read scopes rather than an API key (steps are under "Register Google Cloud Storage files" on the official File input methods page). The official example uses the Interactions API, so I follow it here:
# Register a Cloud Storage file with the File API (follows the official example)
import google.auth
from google import genai
credentials, project = google.auth.default(scopes=[
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/devstorage.read_only",
])
client = genai.Client(credentials=credentials)
registered = client.files.register_files(uris=["gs://my_bucket/manual.pdf"])
for f in registered.files:
interaction = client.interactions.create(
model="gemini-4-hydrogen",
input=[
{"type": "text", "text": "Summarize this document."},
{"type": "document", "uri": f.uri, "mime_type": f.mime_type},
],
)I haven't run registration in production yet, and I haven't verified what happens after the 30 days. If your long-lived originals are already organized in Cloud Storage, it should be lighter to manage than Pattern 2, which is why it's next on my list to try.
For files under 15 MB that you can expose via a public or signed URL, passing an external URL is another option. The docs note that pages behind a login or paywall can't be fetched, and a URL that fails the safety check returns URL_RETRIEVAL_STATUS_UNSAFE.
Pattern 4: cut long batches to fit inside the window
When one video feeds a summary, tags, scene detection and subtitles in sequence, passing the same name around saves both transfer and tokens. That's what the File API is really for.
The thing to watch is that the whole job stays under 48 hours. I treat "upload → process → delete" as one unit and call get_or_upload at the start of each unit. If the queue backs up and a job slips to the next day, it just re-uploads at the top. Deleting files with files.delete when you're done also keeps you well away from the 20 GB ceiling.
The concrete flow for subtitles is in generating multilingual SRT/VTT subtitles from video, which uses this same unit idea.
Common misconceptions
"Restarting the server deletes the files." Restarts have nothing to do with it. Files go away 48 hours after upload; the restart just makes your app re-read stale names. Without a restart, you'd hit the same failure at the 48-hour mark anyway.
"A missing file returns 404." If you only branch on 404, you'll miss the 403 that actually comes back. In forum reports and in my own logs, expired files returned PERMISSION_DENIED with the "may not exist" message. Branch on whether files.get succeeds, not on the number.
"Files in the File API can be retrieved later." Files you uploaded can't be downloaded. The File API is a staging area for the model, not a storage bucket.
The line I drew afterward
That morning, my schema had the File name sitting right next to the primary key, as if it were the image's ID. Tests finished in a few hours, so they never hit the window; it only surfaced in production after two days. Even after fixing it, I nearly repeated the same design in another feature, and every code review for a while came with a knot in my stomach.
Now the rule is simple: the original's location goes in the database; the File name goes in a cache. If I feel the urge to write a File name into the database, I take it as a sign that what I actually need to store is where the original lives. Since holding to that, no more early-morning alerts.
Where you'll likely get stuck next
Once expiry is handled, the next errors tend to come from the files themselves. For INVALID_ARGUMENT when sending images in batches, see diagnosing INVALID_ARGUMENT in batch image analysis. For long videos that end in DEADLINE_EXCEEDED, see what to check first when DEADLINE_EXCEEDED keeps happening. And if you're referencing the same large document over and over, the caching strategy notes may cost less than shuttling it through the File API.
If you do one thing, find a single place in your code that stores a File name and add a files.get check right before it's used. That alone surfaces most next-morning failures before they happen.