Weather Forecast Hourly¶
Setup¶
Weather Forecast Hourly entry point¶
URL: |
|
Example¶
These are complete working examples in several different languages, showing how to use the weather REST API. You can try them right now.
Linux terminal / Windows command prompt:
curl "https://weather.magiclaneapis.com/v1/WeatherForecastHourly" -X POST -H "Content-Type: application/json" -H "Authorization: YOUR_API_KEY_TOKEN" -d @payload.json
Linux note - do not use @~/payload.json instead of @/home/user/payload.json
because ~
does not resolve due to the @
;
use only relative path @payload.json
or absolute path @/home/user/payload.json
where
payload.json
is a text file containing the following:
complete payload.json
file -
coords
, one or more semicolon ; separated latitude,longitude coordinate pairs - the weather will be returned for each one separately;
noHours
- Number of hours for which to return the hourly weather forecast.
details
- 0 returns weather description and temperature (default), 1 - returns all available weather parameters.
1{
2 "coords": "43.0, 2.0; 42.6, 2.5; 42.3, 3.111",
3 "noHours": 4,
4 "details": 0
5}
complete weather request in python
with all default values shown explicitly -
note that the json is stored in the response variable, not printed
directly, so formatting the json output is done locally by the json.dumps()
function instead;
coords
, one or more semicolon ; separated latitude,longitude coordinate pairs - the weather will be returned for each one separately;
noHours
- Number of hours for which to return the hourly weather forecast.
details
- 0 returns weather description and temperature (default), 1 - returns all available weather parameters.
1import requests
2import json
3
4url = "https://weather.magiclaneapis.com/v1/WeatherForecastHourly"
5headers = {"Content-Type": "application/json", "Authorization": "YOUR_API_KEY_TOKEN" }
6payload = {
7 "coords": "43.0, 2.0; 42.6, 2.5; 42.3, 3.111",
8 "noHours": 4,
9 "details": 0
10}
11response = requests.post(url, json=payload, headers=headers)
12r = response.json()
13print(json.dumps(r, indent=3))
This C example uses libcurl
which can be installed on Linux (debian/ubuntu flavors), for example, like this:
sudo apt install libcurl4-gnutls-dev
Save the following code in a text file named weather.c
using your favorite text editor, such as vi
or geany
,
without the line numbers, those are only for reference:
complete weather request in C
with all default values shown explicitly -
coords
, one or more semicolon ; separated latitude,longitude coordinate pairs - the weather will be returned for each one separately;
noHours
- Number of hours for which to return the hourly weather forecast.
details
- 0 returns weather description and temperature (default), 1 - returns all available weather parameters.
1#include <curl/curl.h>
2
3int main (int argc, char *argv[])
4{
5 CURL *curl;
6 CURLcode res;
7
8 curl_global_init(CURL_GLOBAL_ALL);
9 curl = curl_easy_init();
10 if (curl == NULL) { return 128; }
11
12 char* jsonObj = "{"
13 "\"coords\": \"43.0, 2.0; 42.6, 2.5; 42.3, 3.111\","
14 "\"noHours\": 4,"
15 "\"details\": 0"
16 "}";
17 struct curl_slist *headers = NULL;
18 curl_slist_append(headers, "Content-Type: application/json");
19 curl_slist_append(headers, "Authorization: YOUR_API_KEY_TOKEN");
20
21 curl_easy_setopt(curl, CURLOPT_URL, "https://weather.magiclaneapis.com/v1/WeatherForecastHourly");
22 curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "PUT");
23 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
24 curl_easy_setopt(curl, CURLOPT_POSTFIELDS, jsonObj);
25
26 res = curl_easy_perform(curl);
27
28 curl_easy_cleanup(curl);
29 curl_global_cleanup();
30 return res;
31}
Compile the program - for example, on Linux, at the terminal/command prompt type:
gcc weather.c -lcurl -o weather
A binary executable named weather
is created which can be run like this to
send the JSON POST request to the REST API endpoint, receive, and print the response:
./weather
To install D on Linux (debian/ubuntu flavors), at a terminal/command prompt type:
sudo apt install gdc
D can be downloaded for other platforms from this link
complete weather request in D
with all default values shown explicitly -
coords
, one or more semicolon ; separated latitude,longitude coordinate pairs - the weather will be returned for each one separately;
noHours
- Number of hours for which to return the hourly weather forecast.
details
- 0 returns weather description and temperature (default), 1 - returns all available weather parameters.
copy and paste this code in a text file
named weather.d
, without the line numbers - those are for reference:
1import std.stdio;
2import std.net.curl;
3void main()
4{
5 string payload = '{
6 "coords": "43.0, 2.0; 42.6, 2.5; 42.3, 3.111",
7 "noHours": 4,
8 "details": 0
9 }';
10 auto http = HTTP();
11 http.addRequestHeader("Content-Type", "application/json");
12 http.addRequestHeader("Authorization", "YOUR_API_KEY_TOKEN");
13 auto content = post("https://weather.magiclaneapis.com/v1/WeatherForecastHourly", payload, http);
14 writeln(content);
15}
Compile the program - for example, on Linux, at the terminal/command prompt type:
gdc weather.d -o weather
A binary executable named weather
is created which can be run like this to
send the JSON POST request to the REST API endpoint, receive, and print the response:
./weather
To install Julia on Linux (debian/ubuntu flavors), at a terminal/command prompt type:
sudo apt install julia
Julia can be downloaded for other platforms from this link
To start Julia, type:
julia
To install the JSON and HTTP packages, at the Julia prompt type:
import Pkg; Pkg.add("JSON"); Pkg.add("HTTP")
complete weather request in Julia
with all default values shown explicitly -
coords
, one or more semicolon ; separated latitude,longitude coordinate pairs - the weather will be returned for each one separately;
noHours
- Number of hours for which to return the hourly weather forecast.
details
- 0 returns weather description and temperature (default), 1 - returns all available weather parameters.
copy and paste this code at the Julia prompt, without the line numbers - those are for reference:
1using JSON, HTTP
2req = """{
3 "coords": "43.0, 2.0; 42.6, 2.5; 42.3, 3.111",
4 "noHours": 4,
5 "details": 0
6 }"""
7ans = HTTP.request("POST", "https://weather.magiclaneapis.com/v1/WeatherForecastHourly",
8 ["Content-Type" => "application/json",
9 "Authorization" => "YOUR_API_KEY_TOKEN"], req);
10str = String(ans.body);
11print(str)
The free IntelliJ IDEA Community Edition IDE can be downloaded from this link
Create a new kotlin
project in IntelliJ.
In your new kotlin project, browse to src
-> main
-> kotlin
-> Main.kt
Delete all the code in Main.kt
and replace it with the kotlin weather request code shown below:
(without the line numbers - those are only for reference)
complete weather request in kotlin
with all default values shown explicitly -
coords
, one or more semicolon ; separated latitude,longitude coordinate pairs - the weather will be returned for each one separately;
noHours
- Number of hours for which to return the hourly weather forecast.
details
- 0 returns weather description and temperature (default), 1 - returns all available weather parameters.
1package kot.weather.post
2
3import java.net.URI
4import java.net.http.HttpClient
5import java.net.http.HttpRequest
6import java.net.http.HttpResponse
7
8fun main()
9{
10 val request: String = """
11 {
12 "coords": "43.0, 2.0; 42.6, 2.5; 42.3, 3.111",
13 "noHours": 4,
14 "details": 0
15 }"""
16 print(request)
17 val client = HttpClient.newBuilder().build();
18 val postrequest = HttpRequest.newBuilder()
19 .uri(URI.create("https://weather.magiclaneapis.com/v1/WeatherForecastHourly"))
20 .header("Content-Type", "application/json")
21 .header("Authorization", "YOUR_API_KEY_TOKEN")
22 .POST(HttpRequest.BodyPublishers.ofString(request))
23 .build()
24 val response = client.send(postrequest, HttpResponse.BodyHandlers.ofString());
25 println(response.statusCode())
26 println(response.body())
27}
kotlin
weather request!File->Project Structure
and in the left panel select Modules
and then in the right panel select the Dependencies
tab and make sure the
[x] KotlinJavaRuntime
box is checked, then click Apply and OK,
and run the example again.The free IntelliJ IDEA Community Edition IDE can be downloaded from this link
Create a new groovy
project in IntelliJ.
In your new groovy project, browse to src
-> Main.groovy
Delete all the code in Main.groovy
and replace it with the groovy weather request code shown below:
(without the line numbers - those are only for reference)
complete weather request in groovy
with all default values shown explicitly -
coords
, one or more semicolon ; separated latitude,longitude coordinate pairs - the weather will be returned for each one separately;
noHours
- Number of hours for which to return the hourly weather forecast.
details
- 0 returns weather description and temperature (default), 1 - returns all available weather parameters.
1static void main(String[] args)
2{
3 def post = new URL("https://weather.magiclaneapis.com/v1/WeatherForecastHourly").openConnection();
4 def message = '''
5 {
6 "coords": "43.0, 2.0; 42.6, 2.5; 42.3, 3.111",
7 "noHours": 4,
8 "details": 0
9 }
10 '''
11 post.setRequestMethod("POST")
12 post.setDoOutput(true)
13 post.setRequestProperty("Content-Type", "application/json")
14 post.setRequestProperty("Authorization", "YOUR_API_KEY_TOKEN")
15 post.getOutputStream().write(message.getBytes("UTF-8"));
16 def postRC = post.getResponseCode();
17 println(postRC);
18 if (postRC.equals(200)) {
19 println(post.getInputStream().getText());
20 }
21}
groovy
weather request!The free IntelliJ IDEA Community Edition IDE can be downloaded from this link
Create a new scala
project in IntelliJ.
If Language: Scala is not listed in the create new project dialog, click on + to the right
of the listed languages and select Scala
to install the plugin, then restart intellij,
create a new project and select Language: Scala.
In your new scala project, browse to the build.sbt
file and add this line:
libraryDependencies += "org.scalaj" % "scalaj-http_2.13" % "2.4.2"
Note - at the time of this writing, the latest scala version is 2.13
;
the scalaVersion
you see in build.sbt must match the scalaj-http_2.13
version;
if the scalaVersion
you see in build.sbt is newer than 2.13
,
such as 2.18 for example, then go to
https://mvnrepository.com/artifact/org.scalaj/scalaj-http
to see the latest scalaj-http_2.18 version, such as 2.5.6 for example, and replace 2.4.2 with that version, as well as scalaj-http_2.13 with scalaj-http_2.18
A notification button appears within the window to the right - Load sbt Changes
-
click this floating button to update.
In your new scala project, browse to src
-> Main.scala
Delete all the code in Main.scala
and replace it with the scala weather request code shown below:
(without the line numbers - those are only for reference)
complete weather request in scala
with all default values shown explicitly -
coords
, one or more semicolon ; separated latitude,longitude coordinate pairs - the weather will be returned for each one separately;
noHours
- Number of hours for which to return the hourly weather forecast.
details
- 0 returns weather description and temperature (default), 1 - returns all available weather parameters.
1import scalaj.http.{Http, HttpOptions}
2object Main
3{
4 def main(args: Array[String]): Unit =
5 {
6 val request = s"""
7 {
8 "coords": "43.0, 2.0; 42.6, 2.5; 42.3, 3.111",
9 "noHours": 4,
10 "details": 0
11 }
12 """
13 val result = Http("https://weather.magiclaneapis.com/v1/WeatherForecastHourly")
14 .header("Content-Type", "application/json")
15 .header("Authorization", "YOUR_API_KEY_TOKEN")
16 .header("Accept-Encoding", "text")
17 .postData(request)
18 .option(HttpOptions.method("POST"))
19 .option(HttpOptions.readTimeout(10000)).asString
20 println(result)
21 println(result.code)
22 }
23}
scala
weather request!JSONPostReq.java
and then
compiled; at the commandline on either a Linux terminal or Windows command prompt type:javac JSONPostReq.java
java JSONPostReq
complete weather request in java
with all default values shown explicitly -
coords
, one or more semicolon ; separated latitude,longitude coordinate pairs - the weather will be returned for each one separately;
noHours
- Number of hours for which to return the hourly weather forecast.
details
- 0 returns weather description and temperature (default), 1 - returns all available weather parameters.
1import java.net.HttpURLConnection;
2import java.net.URL;
3import java.nio.charset.StandardCharsets;
4import java.io.BufferedReader;
5import java.io.InputStreamReader;
6import java.io.OutputStream;
7import java.io.IOException;
8public class JSONPostReq
9{
10 public static void main(String[] args) throws IOException
11 {
12 URL url = new URL("https://weather.magiclaneapis.com/v1/WeatherForecastHourly");
13 HttpURLConnection connection = (HttpURLConnection) url.openConnection();
14 connection.setRequestMethod("POST");
15 connection.setDoOutput(true);
16 connection.setRequestProperty("Content-Type","application/json");
17 connection.setRequestProperty("Authorization","YOUR_API_KEY_TOKEN");
18 String payload = "{"
19 +"\"coords\": \"43.0, 2.0; 42.6, 2.5; 42.3, 3.111\","
20 +"\"noHours\": 4,"
21 +"\"details\": 0"
22 +"}";
23 byte[] out = payload.getBytes(StandardCharsets.UTF_8);
24 OutputStream stream = connection.getOutputStream();
25 stream.write(out);
26 int responseCode = connection.getResponseCode();
27 System.out.println("response code: "+responseCode);
28 if (responseCode == HttpURLConnection.HTTP_OK)
29 {
30 BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
31 String inputLine;
32 while ((inputLine = in.readLine()) != null)
33 {
34 System.out.println(inputLine.toString());
35 }
36 in.close();
37 }
38 connection.disconnect();
39 }
40}
weather.js
and run at the commandline using nodejs.
In Linux, for example, if nodejs is not installed, it can be installed at the terminal commandline like this:sudo apt install nodejs
npm install xhr2
weather.js
can be run at the commandline like this:nodejs weather.js
complete weather request in javascript
with all default values shown explicitly -
coords
, one or more semicolon ; separated latitude,longitude coordinate pairs - the weather will be returned for each one separately;
noHours
- Number of hours for which to return the hourly weather forecast.
details
- 0 returns weather description and temperature (default), 1 - returns all available weather parameters.
1var XMLHttpRequest = require("xhr2");
2const xhr = new XMLHttpRequest();
3xhr.open("POST", "https://weather.magiclaneapis.com/v1/WeatherForecastHourly");
4xhr.setRequestHeader("Content-Type","application/json");
5xhr.setRequestHeader("Authorization","YOUR_API_KEY_TOKEN");
6const body = JSON.stringify({
7 "coords": "43.0, 2.0; 42.6, 2.5; 42.3, 3.111",
8 "noHours": 4,
9 "details": 0
10});
11xhr.onload = () => {
12 console.log((xhr.responseText));
13};
14xhr.send(body);
weather.go
and run at the commandline using go.
In Linux, for example, if go is not installed, it can be installed at the terminal commandline like this:sudo apt install golang
weather.go
can be run at the commandline like this:go run weather.go
complete weather request in go
with all default values shown explicitly -
coords
, one or more semicolon ; separated latitude,longitude coordinate pairs - the weather will be returned for each one separately;
noHours
- Number of hours for which to return the hourly weather forecast.
details
- 0 returns weather description and temperature (default), 1 - returns all available weather parameters.
1package main
2import (
3 "fmt"
4 "bytes"
5 "net/http"
6 "io/ioutil"
7)
8
9func main() {
10 reqUrl := "https://weather.magiclaneapis.com/v1/WeatherForecastHourly"
11 var data = []byte(`{
12 "coords": "43.0, 2.0; 42.6, 2.5; 42.3, 3.111",
13 "noHours": 4,
14 "details": 0
15 }`)
16 req, _ := http.NewRequest("POST", reqUrl, bytes.NewBuffer(data))
17 req.Header.Add("Content-Type", "application/json")
18 req.Header.Add("Authorization", "YOUR_API_KEY_TOKEN")
19 res, _ := http.DefaultClient.Do(req)
20 defer res.Body.Close()
21 body, _ := ioutil.ReadAll(res.Body)
22 fmt.Println(res)
23 fmt.Println(string(body))
24}
To install dart on Linux (debian/ubuntu flavors), for example, it is best to download the .deb
package from the Linux tab in the above link, such as dart_3.0.5-1_amd64.deb
and install it like this:
sudo dpkg -i dart_3.0.5-1_amd64.deb
At a terminal/command prompt, type:
dart create myapp
to create a new dart application named myapp
. A directory named myapp
is created
in the current directory, containing all necessary files. Go into this new directory:
cd myapp
User your favorite text editor, such as vim
, geany
or notepad
to edit the
pubspec.yaml
file and add this dependency to the dependencies section as shown, then save it:
dependencies:
http: ^1.0.0
Next, edit the dart source code in lib/myapp.dart
to look like this,
without the line numbers - those are for reference only:
complete weather request in dart
with all default values shown explicitly -
coords
, one or more semicolon ; separated latitude,longitude coordinate pairs - the weather will be returned for each one separately;
noHours
- Number of hours for which to return the hourly weather forecast.
details
- 0 returns weather description and temperature (default), 1 - returns all available weather parameters.
1import 'dart:io';
2import 'dart:async';
3import 'dart:convert';
4import 'package:http/http.dart' as http;
5
6calculate() async
7{
8 try
9 {
10 var sendString =
11 {
12 "coords": "43.0, 2.0; 42.6, 2.5; 42.3, 3.111",
13 "noHours": 4,
14 "details": 0
15 };
16 final response = await http.post(
17 Uri.parse("https://weather.magiclaneapis.com/v1/WeatherForecastHourly"),
18 headers: {
19 "Content-Type": "application/json",
20 "Authorization": "YOUR_API_KEY_TOKEN"
21 //"Access-Control-Allow-Origin": "*"
22 },
23 body: jsonEncode(sendString)
24 );
25 print("${response.statusCode}");//2 equivalent ways to print output
26 //print("${response.body}");
27 //print(response.statusCode);
28 print(response.body);
29 }
30 catch(e)
31 {
32 print(e);
33 }
34}
You should replace the string “YOUR_API_KEY_TOKEN” with your actual API key token string.
Now save the lib/myapp.dart
file shown above, go to the myapp
directory, and run it like this:
dart run
sudo apt install perl
sudo cpan JSON
perl
with all default values shown explicitly -coords
, one or more semicolon ; separated latitude,longitude coordinate pairs - the weather will be returned for each one separately;noHours
- Number of hours for which to return the hourly weather forecast.details
- 0 returns weather description and temperature (default), 1 - returns all available weather parameters.weather.pl
(without the line numbers - those are for reference)
and run it:perl weather.pl
1#! /usr/bin/env perl
2use strict;
3use warnings;
4use LWP::UserAgent;
5use HTTP::Request;
6use JSON;
7
8my $url = 'https://weather.magiclaneapis.com/v1/WeatherForecastHourly';
9my $json = '{
10 "coords": "43.0, 2.0; 42.6, 2.5; 42.3, 3.111",
11 "noHours": 4,
12 "details": 0
13 }';
14my $req = HTTP::Request->new( 'POST', $url );
15$req->header( 'Content-Type' => 'application/json',
16'Authorization' => 'YOUR_API_KEY_TOKEN');
17$req->content( $json );
18my $ua = LWP::UserAgent->new;
19my $res = $ua->request( $req );
20print $res->decoded_content;
weather.php
and run at the commandline using php.php
is not installed, it can be installed at the terminal commandline like this:sudo apt install php php-curl
weather.php
can be run at the commandline like this:php weather.php
complete weather request in php
with all default values shown explicitly -
coords
, one or more semicolon ; separated latitude,longitude coordinate pairs - the weather will be returned for each one separately;
noHours
- Number of hours for which to return the hourly weather forecast.
details
- 0 returns weather description and temperature (default), 1 - returns all available weather parameters.
1<?php
2$mycurl = curl_init("https://weather.magiclaneapis.com/v1/WeatherForecastHourly");
3if ($mycurl === false) {
4 print "curl initialization FAILED\n";
5}
6$payload = array(
7 "coords" => "43.0, 2.0; 42.6, 2.5; 42.3, 3.111",
8 "noHours" => 4,
9 "details" => 0
10 );
11$data_string = json_encode($payload);
12curl_setopt($mycurl, CURLOPT_CUSTOMREQUEST, "POST");
13curl_setopt($mycurl, CURLOPT_POSTFIELDS, $data_string);
14curl_setopt($mycurl, CURLOPT_RETURNTRANSFER, true);
15curl_setopt($mycurl, CURLOPT_FOLLOWLOCATION, true);
16curl_setopt($mycurl, CURLOPT_HTTPHEADER, array(
17 "Content-Type: application/json",
18 "Authorization: YOUR_API_KEY_TOKEN"
19 ));
20$result = curl_exec($mycurl);
21
22if ($result === false) {
23 print "POST request FAILED " . curl_error($mycurl) . " errno: " . curl_errno($mycurl) . "\n";
24}
25else { var_dump($result); }
26
27$httpReturnCode = curl_getinfo($mycurl, CURLINFO_HTTP_CODE);
28if ($httpReturnCode != "200") {
29 print "HTTP return code should be 200, got: " . $httpReturnCode . "\n";
30}
31if (is_resource($mycurl)) {
32 curl_close($mycurl);
33}
34?>
sudo apt install r-base-dev
R
httr
package within R like this:install.packages("httr")
complete weather request in R
with all default values shown explicitly -
coords
, one or more semicolon ; separated latitude,longitude coordinate pairs - the weather will be returned for each one separately;
noHours
- Number of hours for which to return the hourly weather forecast.
details
- 0 returns weather description and temperature (default), 1 - returns all available weather parameters.
note that the json is stored in the response variable, not printed
directly, so formatting the json output is done locally by the toJSON()
function: pretty = TRUE
;
(copy and paste the code into the R interpreter, without the line numbers - those are for reference)
1require(httr)
2require(jsonlite)
3body = '{
4 "coords": "43.0, 2.0; 42.6, 2.5; 42.3, 3.111",
5 "noHours": 4,
6 "details": 0
7 }'
8result <- POST("https://weather.magiclaneapis.com/v1/WeatherForecastHourly", body = body,
9add_headers(.headers = c("Content-Type"="application/json", "Authorization"="YOUR_API_KEY_TOKEN")))
10toJSON(content(result), pretty = TRUE)
To exit the R environment, type q()
weather.rb
and run at the commandline using ruby.
In Linux, for example, if ruby is not installed, it can be installed at the terminal commandline like this:sudo apt install ruby
weather.rb
can be run at the commandline like this:ruby weather.rb
complete weather request in ruby
with all default values shown explicitly -
coords
, one or more semicolon ; separated latitude,longitude coordinate pairs - the weather will be returned for each one separately;
noHours
- Number of hours for which to return the hourly weather forecast.
details
- 0 returns weather description and temperature (default), 1 - returns all available weather parameters.
1require "json"
2require "uri"
3require "net/http"
4require "openssl"
5
6url = URI("https://weather.magiclaneapis.com/v1/WeatherForecastHourly")
7http = Net::HTTP.new(url.host, url.port)
8http.use_ssl = true
9request = Net::HTTP::Post.new(url)
10request["Content-Type"] = "application/json"
11request["Accept-Encoding"] = "text"
12request["Authorization"] = "YOUR_API_KEY_TOKEN"
13request.body =
14{
15 "coords": "43.0, 2.0; 42.6, 2.5; 42.3, 3.111",
16 "noHours": 4,
17 "details": 0
18}.to_json
19puts "sent"
20response = http.request(request)
21puts response.read_body
Save the following in a text file named Cargo.toml
(case-sensitive).
This contains the configuration and dependencies required for compilation.
1[package]
2name = "restpost"
3version = "0.1.0"
4edition = "2018"
5
6[[bin]]
7name = "weather"
8path = "weather.rs"
9
10[dependencies]
11json = { version = "0.12.4" }
12reqwest = { version = "0.11.18", features = ["json", "blocking"] }
13serde_json = { version = "1.0.44" }
14tokio = { version = "1.28.2", features = ["macros", "full"] }
weather request with all default values shown explicitly;
coords
, one or more semicolon ; separated latitude,longitude coordinate pairs - the weather will be returned for each one separately;
noHours
- Number of hours for which to return the hourly weather forecast.
details
- 0 returns weather description and temperature (default), 1 - returns all available weather parameters.
Save the following rust program in a text file named weather.rs
1extern crate reqwest;
2#[tokio::main]
3async fn main() -> Result<(), reqwest::Error>
4{
5 let response = reqwest::Client::new()
6 .post("https://weather.magiclaneapis.com/v1/WeatherForecastHourly")
7 .header("Authorization", "YOUR_API_KEY_TOKEN")
8 .header("Content-Type", "application/json")
9 .header("Accept-Encoding", "text")
10 .json(&serde_json::json!({
11 "coords": "43.0, 2.0; 42.6, 2.5; 42.3, 3.111",
12 "noHours": 4,
13 "details": 0
14 }))
15 .send().await?;
16 println!("{:?}",response.text().await?);
17 Ok(())
18}
sudo apt install cargo rustc
Cargo.toml
and weather.rs
:cargo b
cd target/debug
./weather
complete weather request in Matlab
with all default values shown explicitly -
coords
, one or more semicolon ; separated latitude,longitude coordinate pairs - the weather will be returned for each one separately;
noHours
- Number of hours for which to return the hourly weather forecast.
details
- 0 returns weather description and temperature (default), 1 - returns all available weather parameters.
1method = matlab.net.http.RequestMethod.POST
2f0 = matlab.net.http.HeaderField('Content-Type','application/json')
3f1 = matlab.net.http.HeaderField('Authorization','')
4header = [f0 f1]
5str = [ ...
6'{', ...
7 + '"coords": "43.0, 2.0; 42.6, 2.5; 42.3, 3.111",', ...
8 + '"noHours": 4,', ...
9 + '"details": 0,', ...
10 + '}' ]
11request = matlab.net.http.RequestMessage( method, header, jsondecode(str) );
12response = request.send( 'https://weather.magiclaneapis.com/v1/WeatherForecastHourly' );
13jsonencode(response.Body.Data,"PrettyPrint",true)
weather.m
and run at the Matlab
command
prompt by typing weather
and pressing enter. The current working directory shown at the top of the
window should be set to the directory where weather.m
was saved.complete weather request in scilab
with all default values shown explicitly -
coords
, one or more semicolon ; separated latitude,longitude coordinate pairs - the weather will be returned for each one separately;
noHours
- Number of hours for which to return the hourly weather forecast.
details
- 0 returns weather description and temperature (default), 1 - returns all available weather parameters.
note that the json is stored in the result variable, not printed
directly, so formatting the json output is done locally by the toJSON()
function, where 3 is the number of
spaces to use for indentation (if this number is 0, then the json output is not indented/pretty printed)
1jsondata = ...
2"{" ...
3+"coords: 43.0, 2.0; 42.6, 2.5; 42.3, 3.111," ...
4+"noHours: 4," ...
5+"details: 0," ...
6+"}"
7[result, status] = http_post("https://weather.magiclaneapis.com/v1/WeatherForecastHourly", toJSON(fromJSON(jsondata)), format="json", auth="YOUR_API_KEY_TOKEN" );
8toJSON(result,3)
In a linux terminal you can also send the request directly from the command line, without a file, like this: (this method does not work on windows)
1curl "https://weather.magiclaneapis.com/v1/WeatherForecastHourly" -X POST -H "Content-Type: application/json" -H "Authorization: YOUR_API_KEY_TOKEN" -d \
2'{
3...
4}'
The only difference is the added backslash after -d, and then the filename @/home/user/payload.json
is replaced with the contents of
the json file, starting with the next line - note that a single quote ‘ is added before the leading
curly brace { and after the trailing curly brace } to enclose the file contents in single quotes - no backslashes are needed
between the single quotes.
Request parameter definitions¶
Request body schema: |
|
---|---|
key |
value |
(mandatory parameter) |
A list of ; (semicolon) separated latitude,longitude coordinate pairs - the weather will be returned for each separately. Example: “43,2; 42.6,2.5; 42.3,3.1” Type: |
|
Number of hours for which to return the hourly weather forecast. Type: Default value: 48 Maximum value: 240 |
|
Type: Default value: 0 Possible values - 0:returns weather description and temperature; 1:returns all available weather parameters |
Response¶
WeatherForecastHourly results
Each result item is given in a JSON block as shown below.
In the above examples, 3 coordinate pairs were
requested, and 4 hours of hourly forecast, so the result shows
4 hours of hourly weather forecast for each of
the 3 locations specified.
The coordinates are latitude, longitude (degrees).
The date
timestamp field is the UNIX time in seconds
since 1 January 1970 at 00:00.
WindDirection
is in degrees, where 0 is North,
90 is East, 180 is South and 270 is West.
If details
is set to 0, then the parameters
block contains only Temperature
; otherwise, if details
is
set to 1, this block contains all parameters as shown below.
1{
2 "Hourly forecast": [
3 {
4 "UpdateTime": 1699336800,
5 "hourlyWeatherParameters": [
6 {
7 "WeatherConditions": "Cloudy",
8 "date": 1699362000,
9 "daylight": "day",
10 "parameters": {
11 "DewPoint": 1,
12 "FeelsLike": 13,
13 "Humidity": 49,
14 "Pressure": 1020,
15 "Temperature": 13,
16 "UV": 1,
17 "WindDirection": 0,
18 "WindSpeed": 0
19 }
20 },
21 {
22 "WeatherConditions": "Cloudy",
23 "date": 1699365600,
24 "daylight": "day",
25 "parameters": {
26 "DewPoint": 1,
27 "FeelsLike": 13,
28 "Humidity": 50,
29 "Pressure": 1018,
30 "Temperature": 14,
31 "UV": 0,
32 "WindDirection": 201,
33 "WindSpeed": 3
34 }
35 },
36 {
37 "WeatherConditions": "Cloudy",
38 "date": 1699369200,
39 "daylight": "day",
40 "parameters": {
41 "DewPoint": 2,
42 "FeelsLike": 12,
43 "Humidity": 55,
44 "Pressure": 1019,
45 "Temperature": 13,
46 "UV": 0,
47 "WindDirection": 173,
48 "WindSpeed": 3
49 }
50 },
51 {
52 "WeatherConditions": "Cloudy",
53 "date": 1699372800,
54 "daylight": "day",
55 "parameters": {
56 "DewPoint": 3,
57 "FeelsLike": 10,
58 "Humidity": 65,
59 "Pressure": 1020,
60 "Temperature": 11,
61 "UV": 0,
62 "WindDirection": 162,
63 "WindSpeed": 2
64 }
65 }
66 ],
67 "latitude": 43,
68 "longitude": 2
69 },
70 {
71 "UpdateTime": 1699336800,
72 "hourlyWeatherParameters": [
73 {
74 "WeatherConditions": "Partly cloudy",
75 "date": 1699362000,
76 "daylight": "day",
77 "parameters": {
78 "DewPoint": 2,
79 "FeelsLike": 12,
80 "Humidity": 53,
81 "Pressure": 1020,
82 "Temperature": 13,
83 "UV": 1,
84 "WindDirection": 315,
85 "WindSpeed": -1
86 }
87 },
88 {
89 "WeatherConditions": "Partly cloudy",
90 "date": 1699365600,
91 "daylight": "day",
92 "parameters": {
93 "DewPoint": 2,
94 "FeelsLike": 12,
95 "Humidity": 54,
96 "Pressure": 1018,
97 "Temperature": 12,
98 "UV": 0,
99 "WindDirection": 258,
100 "WindSpeed": 3
101 }
102 },
103 {
104 "WeatherConditions": "Light rain",
105 "date": 1699369200,
106 "daylight": "day",
107 "parameters": {
108 "DewPoint": 2,
109 "FeelsLike": 11,
110 "Humidity": 56,
111 "Pressure": 1018,
112 "Temperature": 11,
113 "UV": 0,
114 "WindDirection": 230,
115 "WindSpeed": 3
116 }
117 },
118 {
119 "WeatherConditions": "Light rain",
120 "date": 1699372800,
121 "daylight": "day",
122 "parameters": {
123 "DewPoint": 3,
124 "FeelsLike": 9,
125 "Humidity": 68,
126 "Pressure": 1019,
127 "Temperature": 9,
128 "UV": 0,
129 "WindDirection": 189,
130 "WindSpeed": 2
131 }
132 }
133 ],
134 "latitude": 42.599998474121094,
135 "longitude": 2.5
136 },
137 {
138 "UpdateTime": 1699336800,
139 "hourlyWeatherParameters": [
140 {
141 "WeatherConditions": "Mostly clear",
142 "date": 1699362000,
143 "daylight": "day",
144 "parameters": {
145 "DewPoint": 7,
146 "FeelsLike": 17,
147 "Humidity": 53,
148 "Pressure": 1020,
149 "Temperature": 17,
150 "UV": 1,
151 "WindDirection": 0,
152 "WindSpeed": 0
153 }
154 },
155 {
156 "WeatherConditions": "Light rain",
157 "date": 1699365600,
158 "daylight": "day",
159 "parameters": {
160 "DewPoint": 7,
161 "FeelsLike": 16,
162 "Humidity": 54,
163 "Pressure": 1019,
164 "Temperature": 16,
165 "UV": 0,
166 "WindDirection": 346,
167 "WindSpeed": 7
168 }
169 },
170 {
171 "WeatherConditions": "Mostly cloudy",
172 "date": 1699369200,
173 "daylight": "day",
174 "parameters": {
175 "DewPoint": 7,
176 "FeelsLike": 16,
177 "Humidity": 54,
178 "Pressure": 1018,
179 "Temperature": 16,
180 "UV": 0,
181 "WindDirection": 335,
182 "WindSpeed": 7
183 }
184 },
185 {
186 "WeatherConditions": "Mostly clear",
187 "date": 1699372800,
188 "daylight": "day",
189 "parameters": {
190 "DewPoint": 6,
191 "FeelsLike": 15,
192 "Humidity": 54,
193 "Pressure": 1018,
194 "Temperature": 16,
195 "UV": 0,
196 "WindDirection": 334,
197 "WindSpeed": 6
198 }
199 }
200 ],
201 "latitude": 42.29999923706055,
202 "longitude": 3.1110000610351562
203 }
204 ],
205 "info": {
206 "copyrights": [
207 "MagicLane"
208 ]
209 },
210 "unit": "metric"
211}
Response body schema: |
|
---|---|
key |
value |
|
|
|
|
|
string example: Clear |
|
integer (uint64) example: 1699027963 UNIX timestamp (seconds after 1 January 1970) |
|
string example: day |
|
|
|
integer example: 10 degrees Celsius |
|
integer example: 15 degrees Celsius |
|
integer example: 50 |
|
integer example: 1010 millibars |
|
integer example: 14 degrees Celsius |
|
integer UV index (0-12) |
|
integer degrees: 0=North, 90=East, 180=South, 270=West |
|
integer m/s |
|
integer (uint64) example: 1699027963 UNIX timestamp |
|
double (real number) example: 27.36 |
|
double (real number) example: 44.93 |