Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

440
Vistas
FastAPI - How to upload file via form

I am making a REST API that requires uploading files. For testing purposes, I am uploading files through postman, but I don't know how to access the files on server side. I was able to retrieve the _dict for authentication purposes, but for the file, it returns None.

#arguments - create, delete, view, list, search, upload, download
@app.post("/incident-resource/{service}")
async def incident_resource_service_handler(service, request: Request):
    try:
        session = Session()
        reqDataForm: FormData = await request.form()
        reqData = reqDataForm._dict 

        file = reqDataForm.get('resource')  # in form(key='resource', value=abc.jpeg)
        print(type(file))                   #< class 'NoneType' >

        user = usr_getAuthenticatedUser(session, reqData)
        userRole = getRole(session, user.role_id)
    except Exception as e:
        session.rollback()
        return handleException(e)
over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

As per the documentation, "files will be uploaded as "form data", and you receive them by either declaring the type in your endpoint as bytes or UploadFile. If you need to send additional data along with the file, you may have a look at this answer.

If, however, you need to do that in the way you approach the problem in your question, have a look below. As per Starlette's documentation, you can get the file name and the contents as below. Whatever key name you give on the client side, you have to use that one on the server side as well. Below "upload_file" is used as the key. If multiple, or large size files need to be received and saved, consider using async writing instead, as described here.

server side

@app.post("/upload")
async def create_file(request: Request):
    form = await request.form()
    filename = form["upload_file"].filename
    contents = await form["upload_file"].read()
    with open(filename, 'wb') as f:
        f.write(contents)
    return filename

client side (example using Python requests)

import requests

url = 'http://127.0.0.1:8000/upload'
file = {'upload_file': open('test_files/a.txt','rb')}
resp = requests.post(url=url, files = file) 
print(resp.json())

client side (example using FastAPI's TestClient)

from fastapi.testclient import TestClient
from app import app

client = TestClient(app)
file = {'upload_file': open('test_files/a.txt','rb')}
response = client.post("/upload", files = file)
print(response.json())
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda