Create an OpenAPI definition for a function

REST APIs are often described using an OpenAPI definition (formerly known as a Swagger file). This definition contains information about what operations are available in an API and how the request and response data for the API should be structured.

In this tutorial, you create a function that determines whether an emergency repair on a wind turbine is cost-effective. You then create an OpenAPI definition for the function app so that the function can be called from other apps and services.

In this tutorial, you learn how to:

  • Create a function in Azure
  • Generate an OpenAPI definition using OpenAPI tools
  • Modify the definition to provide additional metadata
  • Test the definition by calling the function


The OpenAPI feature is currently in preview and is only available for version 1.x of the Azure Functions runtime.

Create a function app

You must have a function app to host the execution of your functions. A function app lets you group functions as a logic unit for easier management, deployment, scaling, and sharing of resources.

  1. Select the Create a resource button found on the upper left-hand corner of the Azure portal, then select Compute > Function App.

    Create a function app in the Azure portal

  2. Use the function app settings as specified in the table below the image.

    Define new function app settings

    Setting Suggested value Description
    App name Globally unique name Name that identifies your new function app. Valid characters are a-z, 0-9, and -.
    Subscription Your subscription The subscription under which this new function app is created.
    Resource Group myResourceGroup Name for the new resource group in which to create your function app.
    OS Windows Serverless hosting is currently only available when running on Windows. For Linux hosting, see Create your first function running on Linux using the Azure CLI.
    Hosting plan Consumption plan Hosting plan that defines how resources are allocated to your function app. In the default Consumption Plan, resources are added dynamically as required by your functions. In this serverless hosting, you only pay for the time your functions run. When you run in an App Service plan, you must manage the scaling of your function app.
    Location West Europe Choose a region near you or near other services your functions access.
    Runtime stack Preferred language Choose a runtime that supports your favorite function programming language. Choose .NET for C# and F# functions.
    Storage Globally unique name Create a storage account used by your function app. Storage account names must be between 3 and 24 characters in length and may contain numbers and lowercase letters only. You can also use an existing account, which must meets the storage account requirements.
    Application Insights Default Application Insights is enabled by default. Choose a location near your function app.
  3. Select Create to provision and deploy the function app.

  4. Select the Notification icon in the upper-right corner of the portal and watch for the Deployment succeeded message.

    Define new function app settings

  5. Select Go to resource to view your new function app.


Having trouble finding your function apps in the portal, try adding Function Apps to your favorites in the Azure portal.

Set the Functions runtime version

By default, the function app you create uses version 2.x of the runtime. You must set the runtime version back to 1.x before you create your function.

Use the following procedure to view and update the runtime version currently used by a function app.

  1. In the Azure portal, browse to your function app.

  2. Under Configured Features, choose Function app settings.

    Select function app settings

  3. In the Function app settings tab, locate the Runtime version. Note the specific runtime version and the requested major version. In the example below, the version is set to ~2.

    Select function app settings

  4. To pin your function app to the version 1.x runtime, choose ~1 under Runtime version. This switch is disabled when you have functions in your app.

  5. When you change the runtime version, go back to the Overview tab and choose Restart to restart the app. The function app restarts running on the version 1.x runtime, and the version 1.x templates are used when you create functions.

Create the function

This tutorial uses an HTTP triggered function that takes two parameters: the estimated time to make a turbine repair (in hours); and the capacity of the turbine (in kilowatts). The function then calculates how much a repair will cost, and how much revenue the turbine could make in a 24 hour period.

  1. Expand your function app and select the + button next to Functions. If this is the first function in your function app, select Custom function. This displays the complete set of function templates.

    Functions quickstart page in the Azure portal

  2. In the search field, type http and then choose C# for the HTTP trigger template.

    Choose the HTTP trigger

  3. Type TurbineRepair for the function Name, choose Function for Authentication level, and then select Create.

    Create the HTTP triggered function

  4. Replace the contents of the run.csx file with the following code, then click Save:

    using System.Net;
    const double revenuePerkW = 0.12;
    const double technicianCost = 250;
    const double turbineCost = 100;
    public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
        //Get request body
        dynamic data = await req.Content.ReadAsAsync<object>();
        int hours = data.hours;
        int capacity = data.capacity;
        //Formulas to calculate revenue and cost
        double revenueOpportunity = capacity * revenuePerkW * 24;  
        double costToFix = (hours * technicianCost) +  turbineCost;
        string repairTurbine;
        if (revenueOpportunity > costToFix){
            repairTurbine = "Yes";
        else {
            repairTurbine = "No";
        return req.CreateResponse(HttpStatusCode.OK, new{
            message = repairTurbine,
            revenueOpportunity = "$"+ revenueOpportunity,
            costToFix = "$"+ costToFix

    This function code returns a message of Yes or No to indicate whether an emergency repair is cost-effective, as well as the revenue opportunity that the turbine represents, and the cost to fix the turbine.

  5. To test the function, click Test at the far right to expand the test tab. Enter the following value for the Request body, and then click Run.

    "hours": "6",
    "capacity": "2500"

    Test the function in the Azure portal

    The following value is returned in the body of the response.


Now you have a function that determines the cost-effectiveness of emergency repairs. Next, you generate and modify an OpenAPI definition for the function app.

Generate the OpenAPI definition

Now you're ready to generate the OpenAPI definition. This definition can be used by other Microsoft technologies, like API Apps, PowerApps and Microsoft Flow, as well as third party developer tools like Postman and many more packages.

  1. Select only the verbs that your API supports (in this case POST). This makes the generated API definition cleaner.

    1. On the Integrate tab of your new HTTP Trigger function, change Allowed HTTP methods to Selected methods

    2. In Selected HTTP methods, clear every option except POST, then click Save.

      Selected HTTP methods

  2. Click your function app name (like function-demo-energy) > Platform features > API definition.

    API definition

  3. On the API definition tab, click Function.

    API definition source

    This step enables a suite of OpenAPI options for your function app, including an endpoint to host an OpenAPI file from your function app's domain, an inline copy of the OpenAPI Editor, and an API definition template generator.

  4. Click Generate API definition template > Save.

    Generate API definition template

    Azure scans your function app for HTTP Trigger functions and uses the info in functions.json to generate an OpenAPI definition. Here's the definition that is generated:

    swagger: '2.0'
    version: 1.0.0
    basePath: /
    - https
    - http
        operationId: /api/TurbineRepair/post
        produces: []
        consumes: []
        parameters: []
        description: >-
            Replace with Operation Object
            description: Success operation
            - apikeyQuery: []
    definitions: {}
        type: apiKey
        name: code
        in: query

    This definition is described as a template because it requires more metadata to be a full OpenAPI definition. You'll modify the definition in the next step.

Modify the OpenAPI definition

Now that you have a template definition, you modify it to provide additional metadata about the API operations and data structures. In API definition, delete the generated definition from post to the bottom of the definition, paste in the content below, and click Save.

      operationId: CalculateCosts
      description: Determines if a technician should be sent for repair
      summary: Calculates costs
      x-ms-summary: Calculates costs
      x-ms-visibility: important
        - application/json
        - application/json
        - name: body
          in: body
          description: Hours and capacity used to calculate costs
          x-ms-summary: Hours and capacity
          x-ms-visibility: important
          required: true
            type: object
                description: The amount of effort in hours required to conduct repair
                type: number
                x-ms-summary: Hours
                x-ms-visibility: important
                description: The max output of a turbine in kilowatts
                type: number
                x-ms-summary: Capacity
                x-ms-visibility: important
          description: Message with cost and revenue numbers
          x-ms-summary: Message
           type: object
              type: string
              description: Returns Yes or No depending on calculations
              x-ms-summary: Message 
              type: string
              description: The revenue opportunity cost
              x-ms-summary: RevenueOpportunity 
              type: string
              description: The cost in $ to fix the turbine
              x-ms-summary: CostToFix
        - apikeyQuery: []
definitions: {}
    type: apiKey
    name: code
    in: query

In this case you could just paste in updated metadata, but it's important to understand the types of modifications we made to the default template:

  • Specified that the API produces and consumes data in a JSON format.

  • Specified the required parameters, with their names and data types.

  • Specified the return values for a successful response, with their names and data types.

  • Provided friendly summaries and descriptions for the API, and its operations and parameters. This is important for people who will use this function.

  • Added x-ms-summary and x-ms-visibility, which are used in the UI for Microsoft Flow and Logic Apps. For more information, see OpenAPI extensions for custom APIs in Microsoft Flow.


We left the security definition with the default authentication method of API key. You would change this section of the definition if you used a different type of authentication.

For more information about defining API operations, see the Open API specification.

Test the OpenAPI definition

Before you use the API definition, it's a good idea to test it in the Azure Functions UI.

  1. On the Manage tab of your function, under Host Keys, copy the default key.

    Copy API key


    You use this key for testing, and you also use it when you call the API from an app or service.

  2. Go back to the API definition: function-demo-energy > Platform features > API definition.

  3. In the right pane, click Authenticate, enter the API key that you copied, and click Authenticate.

    Authenticate with API key

  4. Scroll down and click Try this operation.

    Try this operation

  5. Enter values for hours and capacity.

    Enter parameters

    Notice how the UI uses the descriptions from the API definition.

  6. Click Send Request, then click the Pretty tab to see the output.

    Send a request

Next steps

In this tutorial, you learned how to:

  • Create a function in Azure
  • Generate an OpenAPI definition using OpenAPI tools
  • Modify the definition to provide additional metadata
  • Test the definition by calling the function

Advance to the next topic to learn how to create a PowerApps app that uses the OpenAPI definition you created.