0

Trying to set up our first Static Web App in Azure, connecting it to our SQL Server in Azure, but struggling to get off the ground. When I add the "Database Connection (preview)" environment, it says

The database connection configuration file is missing from your repository.

In the Azure portal, we have 3 resources: SQL server, SQL database, and Static Web App.

I've created a dab-config.json, a SWA-4.database.config.json, and a staticwebapp.database.config.json. All 3 files are in my GitHub repository's root level. 3, because it's unclear to my untrained brain if the file prefix needs to match my Static Web App name, if it should just be staticwebapp., or if it should be dab-config.

Github File Structure

All 3 JSON files have the same content

{
  "$schema": "https://github.com/Azure/data-api-builder/releases/download/v1.2.14/dab.draft.schema.json",
  "data-source": {
    "database-type": "mssql",
    "connection-string": "Server=tcp:REMOVED,1433;Initial Catalog=REMOVED;Persist Security Info=False;User ID=REMOVED;Password=REMOVED;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;",
    "options": {
      "set-session-context": false
    }
  },
  "runtime": {
    "rest": {
      "enabled": true,
      "path": "/api",
      "request-body-strict": true
    },
    "graphql": {
      "enabled": true,
      "path": "/graphql",
      "allow-introspection": true
    },
    "host": {
      "cors": {
        "origins": [],
        "allow-credentials": false
      },
      "authentication": {
        "provider": "StaticWebApps"
      },
      "mode": "production"
    }
  },
 "entities": {
........ continued ..............

When I look at my GitHub Actions… one of the Static Web Apps workflows is successful, but the other two, Update dab-config.json and "ci: add Azure Static Web Apps workflow file" both give the same error

The content server has rejected the request with: BadRequest. Reason: No matching Static Web App was found or the api key was invalid."

Workflow Action results

Index.html

<html>
    <head>
        <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline'">
        <script src="/script.js"></script>
    </head>


<button  id="list"  onclick="list()">List</button>

</html>

script.js

async  function  list() {

    const  response = await  fetch('/data-api/rest/VirtuousAI_Matches');
    
    const  data = await  response.json();
    
    console.table(data.value);
}

At this point I'm completely unsure of which step I've messed up. Any help is appreciated

4
  • Actually we don't ask people to share their repos on this site. Questions need to be standalone and clear in their own right. Commented Nov 21, 2024 at 19:10
  • @adam the database connection in the staticwebapp.database.config.json Commented Nov 22, 2024 at 3:40
  • @dab use Static Web Apps CLI to generate a dab configuration file by running swa db init --database-type mssql in local and use dab add Item -c "staticwebapp.database.config.json" --source dbo.ShoppingItems --permissions "anonymous:*" . SO you see Data API will be accessed via <WEB APP URL>/data-api/rest/<ENTITY> Commented Nov 22, 2024 at 3:51
  • @adam Refer to this doc for staticwebapp.database.config.json configuration. Commented Nov 22, 2024 at 3:58

1 Answer 1

0

Below are steps to Publish Azure Static Web Apps with Data API Builder.After writing code for list, get, update, create, and delete in index.html, use the following:

<button  id="list"  onclick="list()">List</button>

async  function  list() {

const  response = await  fetch('/data-api/rest/Person');

const  data = await  response.json();

console.table(data.value);

}

In cmd install the Static Web Apps CLI using the command: npm install -g @azure/static-web-apps-cli .

I referred to this documentation for connecting to a database with Azure Static Web Apps.

Then use the command swa db init --database-type mssql to initialize a database connection for your Azure Static Web App project with a Microsoft SQL Server database.

Open the staticwebapp.database.config.json file and add the following content:

{
  "$schema": "https://github.com/Azure/data-api-builder/releases/latest/download/dab.draft.schema.json",
  "data-source": {
    "database-type": "mssql",
    "options": {
      "set-session-context": false
    },
    "connection-string": "Server=tcp:<your_server>.database.windows.net,1433;Database=<your_db>;User ID=<your_user>;Password=<your_password>;Encrypt=true;"
  },
  "runtime": {
    "rest": {
      "enabled": true,
      "path": "/rest"
    },
    "graphql": {
      "allow-introspection": true,
      "enabled": true,
      "path": "/graphql"
    },
    "host": {
      "mode": "production",
      "cors": {
        "origins": ["*"],
        "allow-credentials": false
      },
      "authentication": {
        "provider": "StaticWebApps"
      }
    }
  },
  "entities": {
    "Person": {
      "source": "dbo.MyTestPersonTable",
      "permissions": [
        {
          "actions": ["*"],
          "role": "anonymous"
        }
      ]
    }
  }
}

I referred to thislink for configuring Azure Static Web Apps and this documentation for swa-cli.config.json.

Use the command swa init to create a swa-cli.config.json file like the following:

{
  "$schema": "https://aka.ms/azure/static-web-apps-cli/schema",
  "configurations": {
    "new-folder-(6)": {
      "appLocation": "scr\\public",
      "outputLocation": ".",
      "dataApiLocation": "swa-db-connections",
      "appDevserverUrl": "http://localhost:4280"
    }
  }
}
  • Create staticwebapp.config.json in the main and add staticwebapp.config.json with the following content:
{
    "navigationFallback": {
      "rewrite": "/index.html",
      "exclude": [
        "/api/*",
        "/static/*"
      ]
    },
    "routes": [
      {
        "route": "/api/*",
        "allowedRoles": ["authenticated"]
      },
      {
        "route": "/admin",
        "allowedRoles": ["admin"]
      },
      {
        "route": "/",
        "rewrite": "/index.html"
      },
      {
        "route": "/static/*",
        "headers": {
          "cache-control": "max-age=31536000"
        }
      }
    ],
    "responseOverrides": {
      "404": {
        "rewrite": "/404.html"
      },
      "403": {
        "rewrite": "/403.html"
      }
    },
    "globalHeaders": {
      "X-Content-Type-Options": "nosniff",
      "Strict-Transport-Security": "max-age=31536000; includeSubDomains; preload",
      "Content-Security-Policy": "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; frame-src 'none';"
    },
    "platform": {
      "apiRuntime": "node:18"
    },
    "networking": {
      "allowedIpRanges": [
        "0.0.0.0/0"
      ]
    }
  }

Create the dbo.MyTestPersonTable in Azure SQL .Allow public network access and allow azure service and sevices to acess the service. Then Start the app locally using:

swa start ./scr/public --data-api-location swa-db-connections 

If you encounter firewall issues during swa start, add the necessary firewall rules in SQL Server.

local output of rest

Push the code, .env, staticwebapp.config.json, swa-cli.config.json, and staticwebapp.database.config.json to GitHub.

push action to web app

Modify the GitHub YAML configuration file as follows, replace app_location according to your folder structure:

 app_location: "./scr/public" 
 api_location: ""
 output_location: "." 

Go to the Database connection in Static Web Apps => link the existing database, and view the app in the browser. linking in azure web app Output: Out of static with rest

Out of data in static

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you so much for all the detail!!! I feel like I'm nearly there. When I run the step of "swa start ......." , after the index.html page loads, then I execute the javascript: GET, I'm receiving a 404. Same with when I manually navigate to the URL: localhost:4280/data-api/rest/myEntityNameHere
Please share your index.html in above questions.
original post (at the bottom) has been updated now with index & javascript
While using separate files for the index and JavaScript, I encountered the same error. To resolve this, I combined both files into a single index.html file. You can refer to my GitHub repository for a sample index.html file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.