Deploy a GraphQL API as an Azure Function
In this article, learn how to deploy an Apollo GraphQL API to Azure in an Azure Function.
This sample demonstrates using the Apollo server in an Azure function to receive a GraphQL query and return the result.
{
hello
}
The server responds with JSON:
{
"hello": "Hello from GraphQL backend"
}
Prepare your development environment
Make sure the following are installed on your local developer workstation:
- An Azure account with an active subscription which you own. Create an account for free.
- Node.js LTS supported by Azure Functions runtime - use the same Node.js version on your local workstation and the deployed Azure Function.
- Visual Studio Code - installed to your local machine.
- Visual Studio Code extensions:
- Azure Functions extension for Visual Studio Code.
- Optional
- Docker: the sample repo includes files to run this sample is a Visual Studio Code dev container ready for local development
- Azurite: local Function app development can use Azurite to satisfy the local.settings.json's requirement for
"AzureWebJobsStorage": "UseDevelopmentStorage=true". - Azure CLI: to remove resources after you completed the following procedure. You can also remove resources with Visual Studio Code.
Clone and run the Azure Function GraphQL sample code
Open a terminal window and
cdto the directory where you want to clone the sample code.Clone the sample code repository:
git clone https://github.com/Azure-Samples/js-e2e-azure-function-graphql-hello.gitOpen that directory in Visual Studio Code:
cd js-e2e-azure-function-graphql-hello && code .Install the project dependencies:
npm installBuild the TypeScript project:
npm run buildRun the sample:
npm startIf your computer pops up a window from a security app asking for permission to run, allow the app.
Query local Azure Function with GraphQL using GraphQL playground
Access the GraphQL playground from the locally running Function app.
Open browser to
http://localhost:7071/api/graphql.On the Apollo Studio page, select Query your server.
Replace example query with the following query:
{ hello }View response:
{ "data": { "hello": "Hello from our GraphQL backend!" } }
Query Azure Function with GraphQL using cURL
In VS Code, open an integrated terminal.
Enter the cURL command:
curl 'http://localhost:7071/api/graphql' \ -H 'content-type: application/json' \ --data-raw '{"query":"{hello}"}' --verboseAt the bottom of the verbose response, view the same GraphQL response.
{ "data": { "hello": "Hello from our GraphQL backend!" } }
Create your Azure Function resource from VS Code
In Visual Studio Code, select the Azure explorer (Shift + Alt + A).
In the Resources section, select the Azure subscription.
Right-click Function App then select Create Function App in Azure (Advanced).
Complete the prompts:
Prompt Enter Enter a globally unique name for the new function app. Enter a unique name, which is used as the subdomain of the URL, such as YOUR-ALIAS-azure-function-graphql-hello.Select a runtime stack. Select a Node LTS runtime stack that matches your local development Node.js version. Select an OS. Select Linux. Select a resource group for new resources. Create a new resource group, such as YOUR-ALIAS-azure-function-graphql.Select a location for new resources. Select a geographic location close to you. Select a hosting plan. Select Consumption. Select a storage account. Create a new storage account. Enter the name of the new storage account. Accept the default value. Select an Application Insights resource for your app. Create new Application Insights resource. Accept the default value. Visual Studio Code's Azure:Activity Log reports when the Function App is created successfully and the workspace shows the Attached Storage Accounts. To use local storage, you need to install Azurite.
Deploy your GraphQL API from VS Code
In Visual Studio Code, still in the Azure explorer (Shift + Alt + A), find your new Azure Function resource under your subscription.
Right-click the resource and select Deploy to Function App.
When asked if you're sure you want to deploy, select Deploy.
Select output window from the notification to watch the deployment.
When the deployment completes, continue to the next section.
Query your GraphQL API with cURL
In VS Code, open an integrated terminal.
Change the cURL command from using your local function to your remove function. Change the URL in the following command to use your Azure Function URL:
curl 'https://YOUR-ALIAS-azure-function-graphql-hello.azurewebsites.net/api/graphql' \ -H 'content-type: application/json' \ --data-raw '{"query":"{hello}"}'The API responds with:
{ "data": { "hello": "Hello from our GraphQL backend!" } }
Review the code
The code used in this article requires the npm package apollo-server-azure-functions to resolve your GraphQL query.
The code for this query is in the ./graphql/index.ts file.
import { ApolloServer, gql} from "apollo-server-azure-functions";
// Construct a schema, using GraphQL schema language
const typeDefs = gql`
type Query {
hello: String
}
`;
// Provide resolver functions for your schema fields
const resolvers = {
Query: {
hello: () => "Hello from our GraphQL backend!",
},
};
// @ts-ignore
const server = new ApolloServer({
typeDefs,
resolvers,
debug: true
});
export default server.createHandler({
cors: {
origin: ['*', "https://studio.apollographql.com"],
methods: ["GET", "POST", "OPTIONS"],
allowedHeaders: ["access-control-allow-credentials", "access-control-allow-origin", "content-type"]
},
});
The highlighted lines are described in the following table:
| Line | Description |
|---|---|
const typeDefs = gql |
Define the GraphQL schema the API supports. |
const resolvers |
Define the GraphQL resolver. hello, from our schema, is given a resolver function to return data from the API: () => "Hello from our GraphQL backend!". |
const server = new ApolloServer({ typeDefs, resolvers }); |
Create an Azure Function version of the Apollo server. |
Troubleshooting graphql API
Use the following troubleshooting guide to resolve any issues.
| Issue | Possible fix |
|---|---|
| cURL command doesn't return anything | In VS Code, expand the Azure Function resource in the Azure explorer. Under the Files node, make sure all your local files have been moved to the remote location and the /dist folder has been generated. If the files aren't present, redeploy the app and watch the deployment output for any errors. If the files do exist, run the cURL command again, adding --verbose to the end of the command to see what status code is returned. |
| API doesn't return anything - but the code is correct. | The Azure Function returns the Apollo server's results if the ./graphql/function.json correctly states the name of the return binding as $return. If you played with the function.json file, make sure the http binding name is reset to the value of $return. Another possible issue is if you changed authLevel, also found in the function.json file from anonymous to another value, you need to either change the value back to anonymous or correctly pass in the authentication when you use the API. |
Did you run into an issue not described in the preceding table? Open an issue to let us know.
Clean up resources
Remove the resources created in this procedure when you're done using them. Because all the resources were created in the same resource group, delete that resource group. In the following procedure, replace YOUR-RESOURCE-GROUP-NAME with your own resource group name.
- In Visual Studio Code, still in the Azure explorer (Shift + Alt + A).
- In the Resources contextual toolbar, select Group by.
- In the list of group-by choices, select Group by Resource Group.
- Right-click on your resource group and select Delete Resource Group*.
Next steps
Povratne informacije
Pošalјite i prikažite povratne informacije za