How to Deploy a Python Serverless Function to Vercel | by Mahbub Zaman | Jan, 2021


In this post, I will be using GitHub and Vercel. First, we will create a git repository so that we can connect it with Vercel.

Here is the link to the repository I’ve created. After you have downloaded the code to your local machine, you can see a python file called inside api folder. According to Vercel’s documentation for Python, if a Python file has a singular HTTP handler variable, inheriting from the BaseHTTPRequestHandler class handler within the api directory, Vercel will serve it as a serverless function.

Let’s break down the individual ingredients of the index.rb file.

from http.server import BaseHTTPRequestHandler
from urllib import parse
class handler(BaseHTTPRequestHandler): def do_GET(self):
s = self.path
dic = dict(parse.parse_qsl(parse.urlsplit(s).query))
if "name" in dic:
message = "Hello, " + dic["name"] + "!"
message = "Hello, stranger!"

For this example, we want to handle the query string. If you look at the documentation, the path instance variable contains the request path. Now let’s parsed the path variable into a dictionary for our convenience. Moreover, I’ve set the HTTP status code to 200 and the content type as plain text.

The following line looks for a key called name in the dictionary. If the key is present, the variable message will contain Hello, followed by the name!, otherwise Hello, stranger!. You can read more about advanced Python usage from here. Finally, I’m returning the encoded content of the message, which is utf-8 by default.

Now, let’s go to Vercel so we can import our project.

Click continue

Once you have clicked Continue, you should see the following dialogue.

Put your git repository link

In my case, I’m going to use my git repository link, which is Now click Continue and finally click Deploy.

Read More …


Write a comment