Please provide steps to implement url shortener via Azure CLI.

Sharma, Ritika 240 Reputation points
2025-10-16T15:17:59.8133333+00:00

Please provide steps to implement url shortener via Azure CLI. Detailed steps, along with deployment.

Azure Functions
Azure Functions
An Azure service that provides an event-driven serverless compute platform.
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Pravallika KV 165 Reputation points Microsoft External Staff Moderator
    2025-10-23T13:31:55.5066667+00:00

    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, click Test/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.

    image

    • You will get an url with shortcode as output.

    image

    • 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.

    image

    Hope it helps!


    Please do not forget to click "Accept the answer” and Yes, this can be beneficial to other community members.

    User's image

    If you have any other questions, let me know in the "comments" and I would be happy to help you.


Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.