pythonswaggerbase64fastapi

FastAPI request with base64 image body takes too long to get response


Below api took too long to respond(more than 1 minute) in swagger, but the print statement print(len(doc)) prints instantly.

# pip install fastapi
# fastapi dev main.py
from fastapi import FastAPI
from typing import Any, Dict
app = FastAPI()

@app.post("/fast")
async def root(data:Dict[Any,Any]):
    doc = data['doc']
    print(len(doc)) # 1459305
    return {"success":len(doc)}

request body:

{"doc":"JVBERi0xLjMgCjEgMCBvYmoKPDwK..<-- 1459305 total chars-- >.Tk2MzU1NTM4OTY4NGIzYTBlNjIwZjA+XQo+PgpzdGFydHhyZWYKMTA5MzMzNQolJUVPRgo="

I am expecting the response very quickly


Solution

  • the request is slow because i run it in FastAPI - Swagger UI(http://localhost:8000/docs).

    the response is fast when i run in the post man.

    you can also disable the swagger curl response: https://github.com/tiangolo/fastapi/discussions/3853

    import json
    from typing import Optional, Dict, Any
    
    from fastapi import FastAPI
    from fastapi.encoders import jsonable_encoder
    from starlette.responses import HTMLResponse
    from fastapi.staticfiles import StaticFiles
    
    app = FastAPI(docs_url=None, redoc_url=None)
    
    app.mount("/static", StaticFiles(directory="static"), name="static")
    
    
    def get_swagger_ui_html(
        *,
        openapi_url: str,
        title: str,
        swagger_js_url: str = "https://cdn.jsdelivr.net/npm/swagger-ui-dist@3/swagger-ui-bundle.js",
        swagger_css_url: str = "https://cdn.jsdelivr.net/npm/swagger-ui-dist@3/swagger-ui.css",
        swagger_favicon_url: str = "https://fastapi.tiangolo.com/img/favicon.png",
        oauth2_redirect_url: Optional[str] = None,
        init_oauth: Optional[Dict[str, Any]] = None,
    ) -> HTMLResponse:
    
        html = f"""
        <!DOCTYPE html>
        <html>
        <head>
        <link type="text/css" rel="stylesheet" href="{swagger_css_url}">
        <link rel="shortcut icon" href="{swagger_favicon_url}">
        <title>{title}</title>
        </head>
        <body>
        <div id="swagger-ui">
        </div>
        <script src="{swagger_js_url}"></script>
        <!-- `SwaggerUIBundle` is now available on the page -->
        <script>
        const HideCurlPlugin = () => {{
            return {{
                wrapComponents: {{
                    curl: () => () => null
                }}
            }}
        }}
        const ui = SwaggerUIBundle({{
            url: '{openapi_url}',
            plugins: [
                HideCurlPlugin
            ],
        """
    
        if oauth2_redirect_url:
            html += f"oauth2RedirectUrl: window.location.origin + '{oauth2_redirect_url}',"
    
        html += """
            dom_id: '#swagger-ui',
            presets: [
            SwaggerUIBundle.presets.apis,
            SwaggerUIBundle.SwaggerUIStandalonePreset
            ],
            layout: "BaseLayout",
            deepLinking: true,
            showExtensions: true,
            showCommonExtensions: true
        })"""
    
        if init_oauth:
            html += f"""
            ui.initOAuth({json.dumps(jsonable_encoder(init_oauth))})
            """
    
        html += """
        </script>
        </body>
        </html>
        """
        return HTMLResponse(html)
    
    
    @app.get("/docs", include_in_schema=False)
    async def custom_swagger_ui_html():
        return get_swagger_ui_html(
            openapi_url=app.openapi_url,
            title=app.title + " - Swagger UI",
            oauth2_redirect_url=app.swagger_ui_oauth2_redirect_url,
            swagger_js_url="/static/swagger-ui-bundle.js",
            swagger_css_url="/static/swagger-ui.css",
        )
    
    
    @app.get("/users/{username}")
    async def read_user(username: str):
        return {"message": f"Hello {username}"}