This quick test is made to test your basic understanding of making REST calls from Apex classes.

  • You can look at the syntax, bonus points if you don’t.
  • The test should ideally not take more than 20 minutes to solve.
  • All the criteria must be met.
  • The answer is available at Admin2Dev GitHub Repo.
  • The answer and complete breakdown of the program is available at the end of this page.

The Test

Question

Parse a response from Open Weather Map as described in Day 21 of the course. The Class-method should take 1 parameter and output the following in log:

At {city name}, {country name} the weather is currently {temperature in Celsius} or {temperature in Fahrenheit}. The weather seems {weather.description}. Have a nice day!

An example response would be: At London, GB the weather is currently 11.43C or 52.574F. The weather seems broken clouds. Have a nice day!

Also write a Mock and Test Class with 100% code coverage.

Hint

  • You don't need to structure the entire JSON, just bits you want to access
  • Read the documentation available here
  • Return a Map in your method and parse it in System.debug();

Start a timer and note how long you take to solve. Ideally, it should take ~20 minutes, but don’t worry if you go overboard.

Answer

First whitelist the domain https://api.openweathermap.org instead of just https://openweathermap.org or it will throw errors.

OpenWeatherMap Class

public class OpenWeatherMap {

	//Creating the JSON Structure

    public class JSONResponse{
        public List<Weather> weather;
        public sys sys;
        public string name; //city name
        public main main;

    }

    public class Weather {
        public String description; //description of weather
    }

    public class sys{
        public String country; //country name
    }

    public class main {
        public Decimal temp; //Temperature in Kelvin
    }



    public static String getTemperature(String city){ //get temp of a city
        String inputUrl = 'https://api.openweathermap.org/data/2.5/weather?q=' + city + '&appid=f335bb76cf2491f6faef107ae2c265f3'; //first build the URL
        return makeRequest(inputUrl);
    }

    private static String makeRequest(String inputUrl){

        String requestType = 'GET';

        //Build the request
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint(inputUrl);
        request.setMethod(requestType);

        //Make the request
        HttpResponse response = http.send(request);

        //Deserialize the JSON
        JSONResponse result = (JSONResponse) JSON.deserialize(response.getBody(), JSONResponse.class);

        String finalString =  'At ' + result.name + ', ' + result.sys.country + ' the weather is currently ' + (result.main.temp - 273.15) + 'C or ' + ((result.main.temp - 273.15) * 9/5 + 32)+ 'F. The weather seems ' + result.weather[0].description + '. Have a nice day!';
        return finalString;
    }

}
  • While returning the temperature values, we need to convert the temperature from K to C and F. The formulas are a quick search away!

OpenWeatherMapMock Class

@isTest
global class OpenWeatherMapMock implements HttpCalloutMock {
	global HTTPResponse respond(HTTPRequest request) {

        String responseJSON = '{"coord":{"lon":-0.13,"lat":51.51},"weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04n"}],"base":"stations","main":{"temp":284.58,"feels_like":282.54,"temp_min":284.26,"temp_max":285.37,"pressure":998,"humidity":58},"wind":{"speed":0.89,"deg":274,"gust":4.02},"clouds":{"all":55},"dt":1591396997,"sys":{"type":3,"id":2019646,"country":"GB","sunrise":1591328769,"sunset":1591387939},"timezone":3600,"id":2643743,"name":"London","cod":200}';

        HttpResponse response = new Httpresponse();
        response.setStatusCode(200);
        response.setBody(responseJSON); //This is what the mock repsonse will be
        return response;
    }

}

OpenWeatherMapTest Class

@isTest
public class OpenWeatherMapTest {
    static testmethod void testerClass(){

        Test.setMock(HttpCalloutMock.class, new OpenWeatherMapMock()); //This line makes the call to mock response class

        System.assertEquals('At London, GB the weather is currently 11.43C or 52.574F. The weather seems broken clouds. Have a nice day!', OpenWeatherMap.getTemperature('London'));

    }

}
Day 25: Error Handling and Future Callouts