Skip to content
This repository has been archived by the owner on Jul 14, 2022. It is now read-only.

Quick Start: Implement a Controller

jwest-apigee edited this page Sep 5, 2014 · 18 revisions
  • Now we can go ahead and implement the actual controller by creating a file called weather.js in the api/controllers folder.

  • The weather.js file should contain a function that will take in request and response objects, query the Open Weather Map API using the city query parameter and return the current weather conditions. Open Weather returns a JSON object. Finally, we also need to export this function so that it is available to the outside world. We will use the request library to make the request. So, add it to package.json

      "dependencies": {
        "request": ""
      },

    The weather function should look as follows:

'use strict';

var util = require('util');
var request = require('request');

module.exports = {
  weather: weather
}

function weather(req, res) {
  var city = req.swagger.params.city.value;
  var url = "http://api.openweathermap.org/data/2.5/weather?q="+city+"&units=imperial";
  console.log('Executing request: '+url);
  request.get(url).pipe(res);
  };
  • The swagger specification allows us to define both the request and the response model. We defined the request parameters for the weather path above. To specify the response model, we need to add the schema field to our responses.

        responses:
          "200":
            description: Success
            schema:
              $ref: "#/definitions/WeatherResponse"
          default:
            description: Error
            schema:
              $ref: "#/definitions/ErrorResponse"

    In the schema we use the $ref type to refer to another YAML object defined under definitions:

    definitions:
      HelloWorldResponse:
        required:
          - message
        properties:
          message:
            type: string
      ErrorResponse:
        required:
          - message
        properties:
          message:
            type: string
      WeatherResponse:
        required:
          - temp
        properties:
          temp:
            type: float
Clone this wiki locally