Hi Sharma, Ritika,
Thanks for reaching out to Microsoft Q&A,
Follow below steps to implement url shortener via Azure CLI.
- Create a Python Azure function app and a table named "shortlinks" in Storage account linked to function app
- Create a Python Azure function and use below code to implement urlshortner.
import azure.functions as func
import logging
import hashlib
import os
import json
from azure.data.tables import TableServiceClient, UpdateMode
app = func.FunctionApp(http_auth_level=func.AuthLevel.ANONYMOUS)
TABLE_NAME = "shortlinks"
CONN_STR = "<Connectionstring of storage account linked to function app>"
@app.route(route="{shortcode}", methods=["GET", "POST"])
def url_shortener(req: func.HttpRequest) -> func.HttpResponse:
logging.info("URL Shortener function received a request.")
# Initialize Table storage client
service = TableServiceClient.from_connection_string(conn_str=CONN_STR)
table_client = service.create_table_if_not_exists(table_name=TABLE_NAME)
# shorten a URL
if req.method == "POST":
try:
req_body = req.get_json()
long_url = req_body.get("url")
if not long_url:
return func.HttpResponse(
json.dumps({"error": "Missing 'url' field"}),
status_code=400,
mimetype="application/json"
)
except ValueError:
return func.HttpResponse(
json.dumps({"error": "Invalid JSON body"}),
status_code=400,
mimetype="application/json"
)
# Generating short code
short_code = hashlib.md5(long_url.encode()).hexdigest()[:6]
# Store mapping in Table Storage
table_client.upsert_entity({
"PartitionKey": "shortlinks",
"RowKey": short_code,
"long_url": long_url
}, mode=UpdateMode.REPLACE)
# Returning short URL
host = req.headers.get("host", "localhost")
short_url = f"https://{host}/{short_code}"
return func.HttpResponse(
json.dumps({"short_url": short_url}),
status_code=200,
mimetype="application/json"
)
# Redirect to long URL using short code
elif req.method == "GET":
shortcode = req.route_params.get("shortcode")
try:
entity = table_client.get_entity(partition_key="shortlinks", row_key=shortcode)
return func.HttpResponse(
status_code=302,
headers={"Location": entity["long_url"]}
)
except:
return func.HttpResponse(
json.dumps({"error": "Short URL not found"}),
status_code=404,
mimetype="application/json"
)
requirements.txt:
azure-functions
azure-data-tables
- Install the modules by running the command
pip install -r requirements.txt. - Run the function locally.
- Zip your function code and use below command to deploy the function using Azure CLI.
az functionapp deployment source config-zip \
-g <resource_group> \
-n <function_app_name> \
--src <zip_file_path>
- Or you can deploy the function using function core tools command
func azure functionapp publish functionappname
- Open deployed function under
functionapp=>overview, clickTest/Run, replace{short code}with test and provide your url as Json input{"url":"https://www.microsoft.com"}
Run the function by selecting Post request.
- You will get an url with shortcode as output.
- Copy the shortcode and add it to your function url
https://pravufn.azurewebsites.net/api/d696f9. You can run the short url directly in browser, it'll redirect to the url.
Hope it helps!
Please do not forget to click "Accept the answer” and Yes, this can be beneficial to other community members.
If you have any other questions, let me know in the "comments" and I would be happy to help you.