Search code examples
pythonflaskdeploymentvercellarge-language-model

How to deploy a Flask app in Vercel, so that I can use it as an API endpoint


Error: The provided path “~/Desktop/deploy/app.py” is a file, but expected a directory. Please choose a different one. ? In which directory is your code located? ./ 🔗 Linked to my-projects/deploy (created .vercel) 🔍 Inspect: https://vercel.com/aayushpaigwars-projects/deploy/69UJ1cLzH8gkgXAapSANhkD [2s] ✅ Production: https://deploy-3mtixmu03-aayushpaigwar.vercel.app [2s] Error: Unable to find any supported Python versions.

I tried vercel deployment by creating a vercel.json file inside that I entered:

{
    "builds": [
        {
            "src": "./app.py",
            "use": "@vercel/python"
        }
    ],
    "routes": [
        {
            "src": "/(.*)",
            "dest": "/app.py"
        }
    ]
}

Solution

  • There is a really nice Vercel template for Flask.

    Here is how you can do that easily:

    You need to have a "vercel.json" file in the root of the project, with the following content:

    # vercel.json
    
    {
      "rewrites": [
        { "source": "/(.*)", "destination": "/api/index" }
      ]
    }
    

    Then, create a "requirements.txt" file in the root of the project:

    # requirements.txt
    
    Flask==3.0.0
    

    Then, create a "api" folder with the index.py file:

    # api/index.py
    
    from flask import Flask
    
    app = Flask(__name__)
    
    @app.route('/')
    def home():
        return 'Hello, World!'
    
    @app.route('/about')
    def about():
        return 'About'
    

    That's it! now deploy it and everything should work as expected. Just send a GET request to '/' or '/about' and you will see the content.

    Source: https://vercel.com/templates/python/flask-hello-world