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

444
Vistas
FastAPI - dynamic inputs for different data types

I have to create a very generic endpoint for a user. The user may send JSON data or may upload a file to this endpoint.

There are multiple options on how to handle different input types, like Request or UploadFile

I thought about solving it like this (pseudo code):

from enum import Enum

class Multiple(Enum):
    request: Request
    file: UploadFile

@app.post("/")
async def root(Multiple):
    if Multiple == request:
        do xxx 
    else if Multiple == file:
        do yyyy
    else: 
        do zzz

Is there any way to make something like this work?

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

You could do that by checking the Content-Type in the request's headers before parsing the data. Regardless, make sure to handle exceptions, in case the given data is not valid JSON/Form/etc. Also, when uploading the file from the client, make sure to use the same "key" you define in the endpoint; below, that is, upload_file. Thus, the client should use, in Javascript for instance, formData.append("upload_file", fileInput.files[0]);

from json import JSONDecodeError
 
@app.post("/upload")
async def upload(request: Request):
    content_type = request.headers.get('Content-Type')
    if content_type is None:
        return 'No Content-Type provided!'
    elif content_type == "application/json":
        try:
            json = await request.json()
            return json
        except JSONDecodeError:
            return "Invalid JSON data"
    elif content_type.startswith("multipart/form-data"):
        try:
            form = await request.form()
            filename = form["upload_file"].filename
            contents = await form["upload_file"].read()
            return filename
        except Exception as e:
            return "Invalid Form data"
    else:
        return 'Content-Type not supported!'
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