6 min read

OpenWeatherMap Proxy

This is a project I’ve done while doing the freeCodeCamp to get my FCC Front End Certificate.

OpenWeatherMapProxy is a proxy that I wrote to help me solving the Show Local Weather challenge. It acts as passthrough to the OpenWeatherMap APIs which require a secret key.

Open Weather Map Proxy

Open Weather Map Proxy is a simple proxy for the Open Weather Map (OWM) - Current Weather API service. The main reason for a web client to use this proxy is that it allows avoiding the exposure of the appid key, which should in general always be kept private.

Open Weather Map Proxy is wrapping only the Current Weather API service, and I originally coded it to be able to finish a freeCodeCamp challenge (Show Local Weather) because I did not like the idea of exposing the private OWM API key on my CodePen.

The intent of this proxy is, in fact, not to extend the OWM service nor to replace it, but just to facilitate the usage of their APIs for learners who dig into these matters as beginners.

The proxy is made by a script which will be running on the current logged-in Google user quota for Google Services, read more in the Reading: give me more section.

If you liked this project, or it was just useful to you, please :star: it!

Please, contact me if you have suggestions for improvement.

Mockup me, please

To avoid hammering the good OWM server with test, yet real, requests, while understanding how to set the ajax request, or worse while fixing that CSS, I added an extra query parameter nomockupme which is on purpose defined such as that, if not specified, the proxy goes mockup and returns immediately a sample data, without even contacting the OWM server.

From openweathermap How to get API key (APPID):

Free and Startup accounts have limitation of capacity and data availability. If you do not get respond from server do not try to repeat your request immediately, but only after 10 min. Also we recommend to store your previous request data.

Do not send requests more than 1 time per 10 minutes from one device/one API key. Normally the weather is not changing so frequently.

Debug information

Another extra query parameter is nodebugme which tells the proxy whether to wrap the OWM response into another object with some more information. When you are ready to use the real data, set it to true or 1 and you’ll get the exact format of the OWM response, no additional information (even in the case of nomockupme === 0).

HTTP errors: a little drawback

I could not find a way to set the error code in the HTTP response using the Content Service, therefore even when the OWM service result has an error code, the HTTP error code to the proxy client is always 200 (OK).

One should always check for the cod === 200 in the response object, as shown in the Usage section and the CodePen mentioned in the Examples.

Reading: give me more

Open Weather Map Proxy consists of a single file script Code.gs to be run as a Web App through the Google Apps Script, which is a scripting language based on JavaScript that lets you do (new and cool) things with Google Apps like Docs, Sheets, and Forms, but in this particular case, acts as a mere Content Service.

This also means that the script runs on the current logged-in Google user quota for Google Services.

Have a look at the Quotas for Google Services for URL Fetch calls, and URL Fetch data received (which are the only features used by this proxy).

Make it work

Google Scripts setup

  1. Copy the source code from Code.gs (Pro-tip: click Raw and then Ctrl+a)
  2. Go to Google-Scripts and create a new script (subscribe to the service if it’s your first time)
  3. Paste the proxy source code into the default file named Code.gs (replace the default code you see)
  4. Within the first function getAppID_(), update the returned string value with your private key from Open Weather Map:
      ...
      function getAppID_() {
     // underscore at the end of the function name
     // makes it private
     return "PUT_HERE_YOUR_PERSONAL_KEY_FROM_OPEN_WEATHER_MAP"; // personal app id string (change this with the one you get from OWM)
      }
      ...
    

    such as it will look something like:

      ...
      function getAppID_() {
     // underscore at the end of the function name
     // makes it private
     return "12345678901234567890123456789012"; // personal app id string (change this with the one you get from OWM)
      }
      ...
    

Deploy as Web App

  1. From the main menu, select Publish and then Deploy as web app...
  2. Enter a new project name if asked
  3. Insert a comment for the new Project version
  4. For Execute the app as: select Me (<youremail>)
  5. For Who has access to the app: select Anyone, even anonymous,
  6. Click on Deploy
  7. Agree on the authorization request clicking on Review Permissions and Allow (well, if you trust my code)
  8. You should see the message “This project is now deployed as a web app”
  9. Copy the app URL, from the Current Web app URL: which must end with /exec (be sure to copy the whole of it, till the end): this is the URL of your OWM proxy service! See Usage to know how to use it

Remarks and notes

  • After the web app is deployed, it is always possible to get its URL from the main menu, selecting Publish and then Deploy as web app...: the URL is under Current web app URL:
  • Each time you make any change to the code, you must create a new version (from the main menu File -> Manage Versions, or while deploying, selecting New)
  • If one tries the app URL in the browser, it gets redirected to another working URL, which requires to be authenticate with google services and therefore it can’t be used for an AJAX request (the jQuery thing): the URL provided by the publishing dialog is the one that works, also in an incognito tab of the browser

Usage

Current Weather API


Returns JSON data about the current weather, coming from the Open Weather Map and wrapped in some debug information if the URL param nodebugme is 0, false, or undefined.

  • URL: /

  • Method: GET

  • URL Params

    Required: none

    Optional:

    • nomockupme: if its value is 0, false, or undefined, the response will not contain real data coming from the OWM server (which is then not contacted), but it will be filled with constant, yet consistent values
    • nodebugme: if its value is 0, false, or undefined, the response will be wrapped into another object which contains debug information (e.g. request parameters)
  • Data Params: none

  • Success Response:

    • Code: 200
      Content:
      {  
         "owmwrapper":"lorepirri",
         "nomockupme":false,
         "parameter":{  
            "nodebugme":"0",
            "nomockupme":"0",
            "id":"0"
         },
         "cod":200,
         "openweathermap":{
            ...data from OWM response,
            "cod":200
         }
      }
      
  • Success Response (if nodebugme is true):

    • Code: 200
      Content: { cod : 200, ...data from OWM response }
  • Error Response:

    • Code: 200 (due to Google Scripts limitation)
      Content:
      {  
         "owmwrapper":"lorepirri",
         "nomockupme":false,
         "parameter":{  
            "nodebugme":"0",
            "nomockupme":"0",
            "id":"0"
         },
         "cod":"400",
         "openweathermap":{
            "cod":"400",
            message: "error message"
         }
      }
      
  • Error Response (if nodebugme is true)::

    • Code: 200 (due to Google Scripts limitation)
      Content: { cod : "400", message: "error message" }
  • Sample Call:

    $.ajax({
      url: "https://script.google.com/macros/s/AKfycbzK_moMuvXmDreD9YnNb_K9GfXoTKCHLE85jx_jNd-5tVAl0so/exec?id=0&nomockupme=0&nodebugme=0",
      datatype: 'json',
      error: function(err){
        console.log('error!');
        console.log(err);
      },//error
      success: function(result){
        if (result.cod === 200) {        
          console.log('success!');
        } else {
          console.log('OWM querystring has an error!');        
        }
        console.log(result);
      }//succes
    });
    

Examples

Here with this CodePen you can play with the parameters, and see the reply in your console (open the DevTools in the browser).

See the Pen OpenWeatherMapProxy Usage by Lorenzo (@lorepirri) on CodePen.



If this article was useful to you, please share it using your favorite way for doing it! If you have suggestions of improvement or you’ve found something wrong, please let me know!


You are not being tracked on this website, no analytics, no cookies taken. I am still looking for a good plugin for comments which respects people's privacy. This website is hosted by Gitlab Pages which as far as stated by their general GitLab's privacy policy terms they collects potentially personally-identifying information like Internet Protocol (IP) addresses as mentioned in this thread.