Replicating YouTube Link Detection in Raw API Requests

GeminiKeyAPIFree · Updated 2026-11-24 · 15 min read

Laptop screen showing JSON structure for video input
The JSON structure required to signal a video input in an API request.

When you paste a YouTube URL into Google AI Studio, the interface does not treat it as a simple string of characters. Instead, the system recognizes the pattern, fetches metadata, and prepares a structured multimodal input that allows the model to reference the video content directly. This seamless experience masks the underlying complexity of how modern AI models handle external media references without requiring you to download or encode the video file yourself. The studio interface handles the heavy lifting of parsing the URL and converting it into a format the model understands.

However, when you switch to the raw API, that automatic magic disappears. If you send a standard chat completion request with a YouTube link in the message text, the model sees only a URL string. It cannot watch the video, summarize the audio, or reference visual events unless you explicitly structure the request to indicate that the URL points to a video object rather than plain text. This article explains how to bridge that gap using standard endpoints, ensuring your API calls behave like the studio version. Note that while the model name suggests otherwise, this service is not affiliated with Google, so the behavior may differ slightly from the official Gemini API.

The core distinction lies in how you format your payload. To get the same behavior as the studio interface, you must explicitly define the media type in your request body, often using specific MIME types or structured data blocks. We will walk through the exact JSON structure required to signal video input, ensuring your API calls behave like the studio version. This approach works with any OpenAI-compatible endpoint, including the free tier services available today. By understanding these structures, you can build robust applications that leverage video content without the overhead of manual preprocessing.

Frequently asked questions

What is the difference between a plain text URL and a structured video input?

A plain text URL is just a string of characters within a message. The model reads it as text and may hallucinate video content. A structured video input explicitly tags the URL as a media object, allowing the model to parse it correctly and reference specific timestamps or visual details without guessing.

How does the API detect a YouTube link automatically?

The API does not detect links automatically in raw requests. You must manually structure the request to include the video URL in a specific format, such as a multimodal part with a video MIME type. The studio interface does this automatically behind the scenes for you.

Which is better for video analysis: direct URL or uploaded file?

Direct URLs are better for quick access to public videos because they require no storage or encoding time. Uploaded files are better for private or custom media but require more bandwidth and processing time. Use URLs when the video is publicly accessible on platforms like YouTube.

What is the maximum length for video URLs in API requests?

There is no strict character limit for the URL string itself, but the total token count of your request matters. Long URLs count toward your token limit. Keep the URL clean and ensure the rest of your prompt fits within the model's context window, which is typically 32,000 tokens for this model.

How does this differ from the standard chat completion endpoint?

The standard endpoint treats all input as text by default. To handle video, you must use the multimodal structure within the same endpoint, adding specific content parts that define the media type. This is the only way to signal that a URL refers to a video rather than a website to read.

What is the role of the User-Agent in video requests?

The User-Agent does not affect video detection directly. However, some video platforms may block requests from standard bots. Using a standard browser-like User-Agent ensures that if the model needs to fetch metadata, the request is not blocked by the video host.

Why does my video URL sometimes fail to load?

Failure often occurs if the video is private, requires authentication, or is geo-blocked. The model cannot access content behind a login wall. Ensure the video is publicly accessible and that the URL is complete, including the full path and any necessary query parameters.

How do I structure the JSON for a video request?

You must create a content array with a part object. Inside that part, specify the type as 'video' or use the appropriate MIME type like 'video/youtube'. Include the video URL in the URL field. This structure tells the model to treat the input as media, not text.

Step by step

  1. Prepare the Payload — Create a JSON payload with the model name 'free-ai' and a messages array. Define a user message with a content array containing a text part and a video part. Ensure the User-Agent header is set to avoid 403 errors when using standard libraries.
  2. Structure the Video Input — In the content array, add a part with type 'video' and the video_url field set to the YouTube link. This structure signals to the model that the input is media, not text, enabling video-specific processing and accurate content analysis.
  3. Send the Request — Use the requests library to send a POST request to the /v1/chat/completions endpoint. Include the headers and payload. Check the response status code to ensure the request was successful and handle any errors appropriately.
  4. Process the Response — Parse the JSON response to extract the model's answer. The model should reference the video content directly. If the response is empty, check the video URL for accessibility and ensure the video is public and correctly formatted.

Understanding the Studio vs. API Difference

The Google AI Studio interface provides a polished experience where you can simply paste a YouTube link, and the system handles the rest. It detects the pattern, validates the URL, and prepares the request for the model. This automatic detection is a feature of the UI, not the underlying API model itself. The model receives a structured payload that explicitly marks the video as a distinct input type, separate from the text prompt. This distinction is crucial for getting accurate video summaries or timestamped references.

When you use the raw API, you lose that automatic detection. If you send a simple text message containing a YouTube URL, the model interprets it as a string. It might recognize the URL format, but it does not inherently know that you want it to watch the video. You must explicitly instruct the API that the URL is a video object. This distinction is crucial for getting accurate video summaries or timestamped references. To replicate this, you must manually construct the multimodal payload, mimicking what the studio interface does automatically.

The Role of Multimodal Inputs

Multimodal inputs allow the model to process different types of data, such as text, images, and video, within a single request. In the API, this means structuring your payload to include specific media parts. Each part has a defined type, such as text or video, which guides the model on how to process the content. Without this structure, the model treats everything as text, leading to potential hallucinations or missed details in the video content.

Why Automatic Detection Fails in Raw Requests

Automatic detection requires a client-side component to parse the input and transform it into a structured format. The raw API is a passive endpoint that only sees what you send. If you send a string, it gets a string. To get video behavior, you must manually construct the multimodal payload, mimicking what the studio interface does automatically. This requires a deeper understanding of the API's request structure.

import requests

url = "https://api.geminikeyapifree.com/v1/chat/completions"
headers = {
    "Content-Type": "application/json",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"
}
payload = {
    "model": "free-ai",
    "messages": [{
        "role": "user",
        "content": [
            {"type": "text", "text": "What happens in the first minute of this video?"},
            {"type": "video", "video_url": "https://www.youtube.com/watch?v=dQw4w9WgXcQ"}
        ]
    }]
}
response = requests.post(url, headers=headers, json=payload)
print(response.json())

Structuring the Request for Video

To replicate the studio behavior, you need to structure your request payload correctly. The key is to use a content array within the message object. This array can contain multiple parts, each with a specific type. For video, you typically use a type value that indicates a video object, along with the URL to the video. This structure signals to the model that the input is media, not text, enabling video-specific processing and accurate content analysis.

The exact structure may vary slightly depending on the API implementation, but the general principle remains the same. You define the content as a list of objects, where each object has a type field. For text, the type is 'text'. For video, it might be 'video' or a specific MIME type. The URL is included in the same object, ensuring the model knows where to find the media. This approach works with any OpenAI-compatible endpoint, including the free tier services available today.

Defining the Content Parts

Each part of the content array represents a distinct input type. You can mix text and video in the same request. The text part provides context or instructions, while the video part provides the media. The model processes these parts in order, allowing you to ask specific questions about the video content in the text part. This flexibility allows for complex interactions between text and media.

Including the Video URL

The video URL must be valid and publicly accessible. If the video is private or requires authentication, the model may not be able to access it. The URL should be complete, including the protocol (https://) and the full path. Some APIs may require additional parameters, such as the video ID or timestamp, depending on the implementation. Always verify the URL before sending the request.

Books representing multimedia data types
Multimodal inputs combine text, video, and other media types.

Handling Different Video Formats

While YouTube links are the most common use case, the API can handle other video formats as well. Structured video inputs often support various MIME types, such as MP4, AVI, or WebM. When using direct file URLs, you must ensure the URL points to a direct file download, not a webpage containing the video. The model needs direct access to the media file to process it effectively, so avoid landing pages or embed URLs.

For YouTube links, the API may use a special handler to fetch metadata or transcribe the audio. This is often more efficient than downloading the entire video file. The model can then analyze the transcript or key frames to answer your questions. This approach reduces latency and token usage, making it ideal for long videos where downloading the full file would be impractical. It is also worth noting that this service is not affiliated with Google, so the specific handlers may differ from the official API.

YouTube vs. Direct File URLs

YouTube links are easier to handle because the API can use existing metadata and transcription services. Direct file URLs require the model to process the raw media data, which can be more resource-intensive. Use YouTube links when possible for better performance and accuracy, especially for public content that is widely available.

MIME Types and Content Types

The MIME type in the request helps the model understand the format of the media. For video, common MIME types include 'video/mp4' or 'video/youtube'. The API uses this information to select the appropriate decoder or processor. Ensure the MIME type matches the actual content of the URL to avoid processing errors and ensure accurate results.

Token Usage and Context Limits

Video inputs can consume a significant number of tokens, depending on the length and complexity of the video. When you send a video URL, the model may generate a transcript or extract key frames, which are then included in the context window. This means your token budget is shared between the video content and your text prompt. Be mindful of the total token count to avoid exceeding limits, which can lead to truncated responses or errors.

The context window for this model is 32,000 tokens, with a maximum output of 16,000 tokens. If you send a long video, the transcript or extracted data may consume a large portion of this window. This leaves less room for your text prompt and the model's response. Plan your requests carefully, keeping the text prompt concise to ensure the video content fits within the available space. You can also refer to our guide on why context windows matter for more details.

Estimating Token Usage

Token usage varies based on the video length and the model's processing method. A rough estimate is that each second of video may consume a few tokens in the transcript. For a 10-minute video, this could be several thousand tokens. Monitor your token usage to avoid hitting the daily limit of 10,000 requests or 10,000,000 tokens. Tracking usage helps you optimize your application's efficiency.

Optimizing for Efficiency

To optimize token usage, keep your text prompt short and focused. Use the video URL to provide context, and ask specific questions that require detailed answers. Avoid sending multiple long videos in a single request, as this can quickly exhaust your context window. If you need to analyze multiple videos, split them into separate requests to maintain performance and accuracy.

Diagram showing API and video service connection
How the API connects to video services to fetch metadata.

Error Handling and Troubleshooting

When sending video requests, you may encounter errors such as 429 (rate limit) or 503 (service unavailable). These errors are common when the API is under heavy load or when you exceed your daily quota. If you receive a 429 error, wait for the specified Retry-After time before retrying. For 503 errors, retry after a few seconds, as the service may recover quickly. Understanding these errors is crucial for building robust applications that handle transient failures gracefully.

Another common issue is video access failure. If the video is private or geo-blocked, the model may return an empty response or an error message. Ensure the video is publicly accessible and that the URL is correct. If you are using a direct file URL, verify that the server allows cross-origin requests, as the model may need to fetch the file from a different domain. You can also check our article on reliability of the keyless endpoint for more insights.

Common Error Codes

Error 429 indicates you have exceeded the rate limit of 1 request per second or 10,000 requests per day. Error 503 indicates the service is busy. Both errors require a retry, but with different wait times. Always check the Retry-After header in the response to determine how long to wait before making another request.

Debugging Video Access Issues

If the model cannot access the video, check the URL for correctness and accessibility. Try accessing the URL in a browser to verify it is public. If using a direct file URL, ensure the file is not protected by authentication or firewalls. Some APIs may also require specific headers, such as Referer or User-Agent, to access the media successfully.

Best Practices for Video Analysis

To get the best results from video analysis, provide clear and specific instructions in your text prompt. Ask the model to summarize the video, extract key points, or answer specific questions about the content. The more detailed your instructions, the more accurate the response will be. Avoid vague questions like 'What is this video about?' and instead ask 'What are the three main arguments presented in the video?' to guide the model's focus.

Use the multimodal structure to combine text and video in a single request. This allows the model to reference the video content directly in its response. You can also send multiple video URLs in one request, but be mindful of the token limit. If you need to analyze many videos, consider sending them in batches to stay within your daily quota. For more on managing quotas, see our guide on why quotas reset early.

Crafting Effective Prompts

Your text prompt should guide the model on what to look for in the video. Use keywords that match the video content, such as 'summary', 'key points', or 'transcript'. Be specific about the timeframes you are interested in, if applicable. This helps the model focus on the relevant parts of the video and ignore irrelevant content, leading to more accurate and useful responses.

Combining Text and Video

Mixing text and video in a single request allows for more nuanced analysis. You can provide context in the text part and reference specific events in the video. This approach is particularly useful for comparing different videos or analyzing the relationship between text and media. Ensure the text part is concise to save tokens for the video content, maximizing the efficiency of your request.

Mobile interface showing video and text input
The studio interface automatically structures video inputs for you.

Advanced Techniques and Workarounds

For more advanced use cases, you can combine video analysis with other multimodal inputs, such as images or documents. This allows you to create rich, multi-media prompts that provide context from multiple sources. For example, you can send a video and an image, asking the model to compare the two or extract information from both. This flexibility enables complex workflows that go beyond simple video summarization, allowing for deeper insights.

Another workaround is to use the transcript of the video as a text input if the video URL is not supported. You can generate a transcript using a separate service and include it in the text part of the request. This approach gives you more control over the content processed by the model, but it requires additional steps to generate and format the transcript. It is a reliable fallback when direct video support is limited.

Multi-Modal Workflows

Multi-modal workflows allow you to combine different types of media in a single request. This can include text, images, video, and audio. By mixing these inputs, you can create more comprehensive analyses that leverage the strengths of each media type. For example, you can use an image to provide visual context and a video to provide temporal context, creating a richer narrative.

Using Transcripts as Fallback

If the video URL fails, using a transcript as a fallback is a reliable strategy. Transcripts are text-based and can be processed by any model that supports text input. This ensures that you always have a way to analyze the content of the video, even if the video itself is inaccessible. You can generate transcripts using external services or APIs dedicated to speech-to-text conversion for greater flexibility.

Integrating with Other Tools

Integrating video analysis with other tools can enhance your workflow. For example, you can use a video processing library to extract frames or audio, then send them to the API for analysis. This approach gives you more control over the input data and allows you to preprocess the media before sending it to the model. You can also use the API's response to update a database or trigger other actions in your application, creating a seamless automation pipeline.

Consider using the API's streaming feature to handle large video responses. Streaming allows you to receive the response in chunks, which can be more efficient for long outputs. This is particularly useful when the model generates a detailed transcript or summary of a long video. Streaming also provides a better user experience by showing the response in real-time, keeping users engaged while the analysis completes.

Preprocessing Media

Preprocessing media before sending it to the API can improve accuracy and reduce token usage. You can extract key frames, summarize audio, or filter out noise. This ensures that the model receives only the most relevant information, leading to faster and more accurate responses. Preprocessing also allows you to customize the input to fit the model's strengths, optimizing the overall performance of your application.

Streaming Responses

Streaming responses allow you to receive data in real-time, which is useful for long outputs. This feature is supported by the API and can be enabled by setting the stream parameter to true. Streaming is particularly beneficial for video analysis, where the model may generate a lengthy transcript or summary. It provides a smoother user experience by showing progress as the response is generated, reducing perceived latency.

Bar chart showing token usage for video requests
Token usage increases significantly with video inputs.
Try the free API

Test the model instantly with our keyless endpoint—no credit card, no setup required.

Read also