Archivos Privados desde Backblaze B2 con FastAPI

Aprende a servir archivos privados de Backblaze B2 desde FastAPI sin exponer el bucket ni usar almacenamiento temporal, usando streaming o enlaces firmados.

9 sept 2025 • 2 min read • Q2BSTUDIO Team

Inteligencia-Artificial-

En este artículo explico cómo servir archivos privados almacenados en Backblaze B2 desde un backend con FastAPI, abordando seguridad, rendimiento y buenas prácticas para no exponer directamente el bucket ni usar almacenamiento local temporal.

Objetivo: almacenar archivos en un bucket privado de B2, permitir descargas seguras desde FastAPI, evitar URLs públicas y prevenir cacheo o almacenamiento temporal en el servidor.

Configuración en Backblaze B2: crea un bucket y marca su visibilidad como privada, genera una Application Key con permisos limitados solo a las operaciones necesarias, y toma nota del identificador y la clave para autenticar desde tu backend. Backblaze B2 es una alternativa rentable y compatible con S3 para almacenamiento de objetos.

Conexión desde Python: usa la librería oficial b2sdk para autenticar y acceder a archivos. En lugar de exponer enlaces públicos, tienes dos enfoques recomendados: generar enlaces temporales firmados con permiso de descarga o descargar el archivo desde B2 y servirlo directamente al cliente en streaming. El streaming evita almacenar el archivo en disco y mantiene el control de acceso en tu aplicación.

Patrón seguro con FastAPI: protege la ruta con autenticación y autorización adecuadas, por ejemplo tokens JWT o sesiones. Al recibir una petición válida, autentica con B2 mediante b2sdk, solicita el objeto por nombre o id y transmite el contenido al cliente con un StreamingResponse de FastAPI. Ajusta cabeceras como Content-Disposition para forzar descarga cuando proceda y Cache-Control no-store para evitar cacheo intermedio.

Recomendaciones prácticas: limita permisos de la Application Key a solo lectura para el bucket concreto, registra accesos y errores, aplica límites de tamaño y tiempos de espera en las respuestas, y maneja errores de red o cuotas de B2 con reintentos exponenciales. Para archivos muy grandes considera el streaming por partes y control de ancho de banda.

Ventajas de este enfoque: mantienes el bucket privado sin URLs públicas, controlas la autorización a nivel de aplicación, no dependes de almacenamiento temporal en el servidor y puedes auditar descargas. Backblaze B2 ofrece buena relación coste y compatibilidad con soluciones cloud habituales.

Si necesitas integrar este flujo dentro de una solución más amplia, en Q2BSTUDIO desarrollamos aplicaciones a medida y software a medida que incluyen integración con servicios cloud, seguridad y soluciones de inteligencia artificial. Podemos ayudarte a diseñar la arquitectura que incluya almacenamiento seguro en B2 y un backend con FastAPI optimizado para producción. Conoce nuestros servicios de desarrollo de aplicaciones y software a medida y nuestros servicios cloud para AWS y Azure.

Palabras clave relacionadas: aplicaciones a medida, software a medida, inteligencia artificial, ciberseguridad, servicios cloud aws y azure, servicios inteligencia de negocio, ia para empresas, agentes IA, power bi. Si quieres una solución completa que incluya integración segura de almacenamiento B2 con APIs modernas como FastAPI, contacta a Q2BSTUDIO para una propuesta a medida.

A BREAK?

Play for a moment before you go

OUR SERVICES

How we can help you

Artificial intelligence

AI agents, chatbots, and intelligent assistants that automate tasks and serve your customers 24/7 to improve the efficiency of your business.

More info

Software Development

Web, mobile, and desktop applications, intranets, e-commerce, SaaS, and management platforms designed for your company's specific needs.

More info

Cloud services

Migration, infrastructure, managed hosting, high availability, and security on Microsoft Azure and Amazon Web Services to help your business scale without limits.

More info

Cybersecurity and pentesting

Security audits, penetration testing and protection of applications, data and infrastructure on-premise and cloud, with ethical hacking and regulatory compliance.

More info

Business Intelligence

Dashboards and data analysis with Power BI: we integrate your sources, design dashboards and KPIs and turn your data into decisions.

More info

Process automation

We automate repetitive tasks and connect your applications with n8n, Power Automate, Make, and RPA, eliminating manual work and increasing productivity.

More info

Training for Companies

We train your teams in technology with criteria: web development, databases, Git, best practices and security, automation with n8n, artificial intelligence for companies and creation of AI solutions with Azure AI Foundry.

More info

Code Auditing

We audit the code that you, your team or an AI create: we tell you what is good and what to improve, we secure it and make it ready for production, web or app.

More info

AI Image Generation

We create for you the images that your business needs with artificial intelligence: product, networks, advertising, illustration and avatars. You tell us what you want and we deliver it ready to use.

More info

AI Video Generation

We create videos with artificial intelligence for you: promotional, networking, virtual presenters, dubbing and animations. You tell us the idea and we will deliver it assembled and ready to publish.

More info

AI Conversational Avatars

We create conversational avatars with AI – digital humans with a face and voice – that serve your customers and teams with the knowledge of your company, on your website, interactive monitors, WhatsApp or Teams.

More info

Online Marketing and AI

Google Ads, Meta Ads, LinkedIn Ads and AI Engine Positioning (GEO/AEO): we attract customers and make your brand appear where they search for you, also on ChatGPT, Gemini and Perplexity.

More info

Do you have a project in mind?

Tell us your vision and we'll turn it into a software solution. Whatever the scope, we make your idea real.

Live Chat