Route Weather
In this guide you will learn how to get the weather along a route, for the specific time you will be at each position along the route during navigation.
Setup
First, get an API key token, see the Getting Started guide.
Route Weather entry point
URL: https://weather.magiclaneapis.com/v1/WeatherRoute
EXAMPLE
These are complete working examples in several different languages, showing how to use the weather REST API. You can try them right now.
- curl
- python3
- C
- D
- Julia
- Kotlin
- Groovy
- Scala
- Java
- JavaScript
- Go
- Dart
- Perl
- PHP
- R
- Ruby
- Rust
- Matlab
- Scilab
Linux terminal / Windows command prompt:
curl "https://weather.magiclaneapis.com/v1/WeatherRoute" -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,unix_timestamp_seconds coordinate pairs - the weather will be returned for each one separately; details
- 0 returns weather description and temperature (default), 1 - returns all available weather parameters.
{
"coords": "43.0, 2.0, 1699512512; 42.6, 2.5, 1699512712; 42.3, 3.111, 1699512912",
"details": 0
}
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,unix_timestamp_seconds coordinate pairs - the weather will be returned for each one separately; details
- 0 returns weather description and temperature (default), 1 - returns all available weather parameters.
import requests
import json
url = "https://weather.magiclaneapis.com/v1/WeatherRoute"
headers = {"Content-Type": "application/json", "Authorization": "YOUR_API_KEY_TOKEN" }
payload = {
"coords": "43.0, 2.0, 1699512512; 42.6, 2.5, 1699512712; 42.3, 3.111, 1699512912",
"details": 0
}
response = requests.post(url, json=payload, headers=headers)
r = response.json()
print(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,unix_timestamp_seconds coordinate pairs - the weather will be returned for each one separately; details
- 0 returns weather description and temperature (default), 1 - returns all available weather parameters.
#include <curl/curl.h>
int main (int argc, char *argv[])
{
CURL *curl;
CURLcode res;
curl_global_init(CURL_GLOBAL_ALL);
curl = curl_easy_init();
if (curl == NULL) { return 128; }
char* jsonObj = "{"
"\"coords\": \"43.0, 2.0, 1699512512; 42.6, 2.5, 1699512712; 42.3, 3.111, 1699512912\","
"\"details\": 0"
"}";
struct curl_slist *headers = NULL;
curl_slist_append(headers, "Content-Type: application/json");
curl_slist_append(headers, "Authorization: YOUR_API_KEY_TOKEN");
curl_easy_setopt(curl, CURLOPT_URL, "https://weather.magiclaneapis.com/v1/WeatherRoute");
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "PUT");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, jsonObj);
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
curl_global_cleanup();
return res;
}
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
https://dlang.org/download.html
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,unix_timestamp_seconds coordinate pairs - the weather will be returned for each one separately; 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:
import std.stdio;
import std.net.curl;
void main()
{
string payload = '{
"coords": "43.0, 2.0, 1699512512; 42.6, 2.5, 1699512712; 42.3, 3.111, 1699512912",
"details": 0
}';
auto http = HTTP();
http.addRequestHeader("Content-Type", "application/json");
http.addRequestHeader("Authorization", "YOUR_API_KEY_TOKEN");
auto content = post("https://weather.magiclaneapis.com/v1/WeatherRoute", payload, http);
writeln(content);
}
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
https://julialang.org/downloads/
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,unix_timestamp_seconds coordinate pairs - the weather will be returned for each one separately; 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:
using JSON, HTTP
req = """{
"coords": "43.0, 2.0, 1699512512; 42.6, 2.5, 1699512712; 42.3, 3.111, 1699512912",
"details": 0
}"""
ans = HTTP.request("POST", "https://weather.magiclaneapis.com/v1/WeatherRoute",
["Content-Type" => "application/json",
"Authorization" => "YOUR_API_KEY_TOKEN"], req);
str = String(ans.body);
print(str)
https://www.jetbrains.com/idea/download
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,unix_timestamp_seconds coordinate pairs - the weather will be returned for each one separately; details
- 0 returns weather description and temperature (default), 1 - returns all available weather parameters.
package kot.weather.post
import java.net.URI
import java.net.http.HttpClient
import java.net.http.HttpRequest
import java.net.http.HttpResponse
fun main()
{
val request: String = """
{
"coords": "43.0, 2.0, 1699512512; 42.6, 2.5, 1699512712; 42.3, 3.111, 1699512912",
"details": 0
}"""
print(request)
val client = HttpClient.newBuilder().build();
val postrequest = HttpRequest.newBuilder()
.uri(URI.create("https://weather.magiclaneapis.com/v1/WeatherRoute"))
.header("Content-Type", "application/json")
.header("Authorization", "YOUR_API_KEY_TOKEN")
.POST(HttpRequest.BodyPublishers.ofString(request))
.build()
val response = client.send(postrequest, HttpResponse.BodyHandlers.ofString());
println(response.statusCode())
println(response.body())
}
Click the green triangle play button to compile and run the kotlin
weather request!
If there is a problem compiling because of a missing standard library, go in the menu to 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.
https://www.jetbrains.com/idea/download
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,unix_timestamp_seconds coordinate pairs - the weather will be returned for each one separately; details
- 0 returns weather description and temperature (default), 1 - returns all available weather parameters.
static void main(String[] args)
{
def post = new URL("https://weather.magiclaneapis.com/v1/WeatherRoute").openConnection();
def message = '''
{
"coords": "43.0, 2.0, 1699512512; 42.6, 2.5, 1699512712; 42.3, 3.111, 1699512912",
"details": 0
}
'''
post.setRequestMethod("POST")
post.setDoOutput(true)
post.setRequestProperty("Content-Type", "application/json")
post.setRequestProperty("Authorization", "YOUR_API_KEY_TOKEN")
post.getOutputStream().write(message.getBytes("UTF-8"));
def postRC = post.getResponseCode();
println(postRC);
if (postRC.equals(200)) {
println(post.getInputStream().getText());
}
}
Click the green triangle play button to compile and run the groovy
weather request!
https://www.jetbrains.com/idea/download
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,unix_timestamp_seconds coordinate pairs - the weather will be returned for each one separately; details
- 0 returns weather description and temperature (default), 1 - returns all available weather parameters.
import scalaj.http.{Http, HttpOptions}
object Main
{
def main(args: Array[String]): Unit =
{
val request = s"""
{
"coords": "43.0, 2.0, 1699512512; 42.6, 2.5, 1699512712; 42.3, 3.111, 1699512912",
"details": 0
}
"""
val result = Http("https://weather.magiclaneapis.com/v1/WeatherRoute")
.header("Content-Type", "application/json")
.header("Authorization", "YOUR_API_KEY_TOKEN")
.header("Accept-Encoding", "text")
.postData(request)
.option(HttpOptions.method("POST"))
.option(HttpOptions.readTimeout(10000)).asString
println(result)
println(result.code)
}
}
Click the green triangle play button to compile and run the scala
weather request!
The java code shown has to be saved in a text file named JSONPostReq.java
and then compiled; at the commandline on either a Linux terminal or Windows command prompt type:
javac JSONPostReq.java
to compile the program making the json POST request to the Maps REST API, and then run it:
java JSONPostReq
complete weather request in java
with all default values shown explicitly - coords
, one or more semicolon ; separated latitude,longitude,unix_timestamp_seconds coordinate pairs - the weather will be returned for each one separately; details
- 0 returns weather description and temperature (default), 1 - returns all available weather parameters.
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.IOException;
public class JSONPostReq
{
public static void main(String[] args) throws IOException
{
URL url = new URL("https://weather.magiclaneapis.com/v1/WeatherRoute");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type","application/json");
connection.setRequestProperty("Authorization","YOUR_API_KEY_TOKEN");
String payload = "{"
+"\"coords\": \"43.0, 2.0, 1699512512; 42.6, 2.5, 1699512712; 42.3, 3.111, 1699512912\","
+"\"details\": 0"
+"}";
byte[] out = payload.getBytes(StandardCharsets.UTF_8);
OutputStream stream = connection.getOutputStream();
stream.write(out);
int responseCode = connection.getResponseCode();
System.out.println("response code: "+responseCode);
if (responseCode == HttpURLConnection.HTTP_OK)
{
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
{
System.out.println(inputLine.toString());
}
in.close();
}
connection.disconnect();
}
}
The javascript code shown can be saved in a text file such as 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
also XMLHttpRequest needs to be installed:
npm install xhr2
Then 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,unix_timestamp_seconds coordinate pairs - the weather will be returned for each one separately; details
- 0 returns weather description and temperature (default), 1 - returns all available weather parameters.
var XMLHttpRequest = require("xhr2");
const xhr = new XMLHttpRequest();
xhr.open("POST", "https://weather.magiclaneapis.com/v1/WeatherRoute");
xhr.setRequestHeader("Content-Type","application/json");
xhr.setRequestHeader("Authorization","YOUR_API_KEY_TOKEN");
const body = JSON.stringify({
"coords": "43.0, 2.0, 1699512512; 42.6, 2.5, 1699512712; 42.3, 3.111, 1699512912",
"details": 0
});
xhr.onload = () => {
console.log((xhr.responseText));
};
xhr.send(body);
The go code shown can be saved in a text file such as 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
Then 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,unix_timestamp_seconds coordinate pairs - the weather will be returned for each one separately; details
- 0 returns weather description and temperature (default), 1 - returns all available weather parameters.
package main
import (
"fmt"
"bytes"
"net/http"
"io/ioutil"
)
func main() {
reqUrl := "https://weather.magiclaneapis.com/v1/WeatherRoute"
var data = []byte(`{
"coords": "43.0, 2.0, 1699512512; 42.6, 2.5, 1699512712; 42.3, 3.111, 1699512912",
"details": 0
}`)
req, _ := http.NewRequest("POST", reqUrl, bytes.NewBuffer(data))
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Authorization", "YOUR_API_KEY_TOKEN")
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := ioutil.ReadAll(res.Body)
fmt.Println(res)
fmt.Println(string(body))
}
https://dart.dev/get-dart Dart can be downloaded from here
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,unix_timestamp_seconds coordinate pairs - the weather will be returned for each one separately; details
- 0 returns weather description and temperature (default), 1 - returns all available weather parameters.
import 'dart:io';
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
calculate() async
{
try
{
var sendString =
{
"coords": "43.0, 2.0, 1699512512; 42.6, 2.5, 1699512712; 42.3, 3.111, 1699512912",
"details": 0
};
final response = await http.post(
Uri.parse("https://weather.magiclaneapis.com/v1/WeatherRoute"),
headers: {
"Content-Type": "application/json",
"Authorization": "YOUR_API_KEY_TOKEN"
//"Access-Control-Allow-Origin": "*"
},
body: jsonEncode(sendString)
);
print("${response.statusCode}");//2 equivalent ways to print output
//print("${response.body}");
//print(response.statusCode);
print(response.body);
}
catch(e)
{
print(e);
}
}
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
In Linux (debian/ubuntu flavors), for example, if perl is not installed, it can be installed at the terminal commandline like this:
sudo apt install perl
The JSON perl module can be installed like this:
sudo cpan JSON
complete weather request in 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;
details
- 0 returns weather description and temperature (default), 1 - returns all available weather parameters.
save this code in a text file named weather.pl
(without the line numbers - those are for reference) and run it:
perl weather.pl
#! /usr/bin/env perl
use strict;
use warnings;
use LWP::UserAgent;
use HTTP::Request;
use JSON;
my $url = 'https://weather.magiclaneapis.com/v1/WeatherRoute';
my $json = '{
"coords": "43.0, 2.0, 1699512512; 42.6, 2.5, 1699512712; 42.3, 3.111, 1699512912",
"details": 0
}';
my $req = HTTP::Request->new( 'POST', $url );
$req->header( 'Content-Type' => 'application/json',
'Authorization' => 'YOUR_API_KEY_TOKEN');
$req->content( $json );
my $ua = LWP::UserAgent->new;
my $res = $ua->request( $req );
print $res->decoded_content;
The php code shown can be saved in a text file such as weather.php
and run at the commandline using php.
In Linux (debian/ubuntu flavors), for example, if php
is not installed, it can be installed at the terminal commandline like this:
sudo apt install php php-curl
Then 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,unix_timestamp_seconds coordinate pairs - the weather will be returned for each one separately; details
- 0 returns weather description and temperature (default), 1 - returns all available weather parameters.
<?php
$mycurl = curl_init("https://weather.magiclaneapis.com/v1/WeatherRoute");
if ($mycurl === false) {
print "curl initialization FAILED\n";
}
$payload = array(
"coords" => "43.0, 2.0, 1699512512; 42.6, 2.5, 1699512712; 42.3, 3.111, 1699512912",
"details" => 0
);
$data_string = json_encode($payload);
curl_setopt($mycurl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($mycurl, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($mycurl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($mycurl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($mycurl, CURLOPT_HTTPHEADER, array(
"Content-Type: application/json",
"Authorization: YOUR_API_KEY_TOKEN"
));
$result = curl_exec($mycurl);
if ($result === false) {
print "POST request FAILED " . curl_error($mycurl) . " errno: " . curl_errno($mycurl) . "\n";
}
else { var_dump($result); }
$httpReturnCode = curl_getinfo($mycurl, CURLINFO_HTTP_CODE);
if ($httpReturnCode != "200") {
print "HTTP return code should be 200, got: " . $httpReturnCode . "\n";
}
if (is_resource($mycurl)) {
curl_close($mycurl);
}
?>
In Linux (debian/ubuntu flavors), for example, if R is not installed, it can be installed at the terminal commandline like this:
sudo apt install r-base-dev
Then start the R interpreter environment like this:
R
install the httr
package within R like this:
install.packages("httr")
and answer y to the two installation-related questions that follow;
complete weather request in R
with all default values shown explicitly - coords
, one or more semicolon ; separated latitude,longitude,unix_timestamp_seconds coordinate pairs - the weather will be returned for each one separately; 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)
require(httr)
require(jsonlite)
body = '{
"coords": "43.0, 2.0, 1699512512; 42.6, 2.5, 1699512712; 42.3, 3.111, 1699512912",
"details": 0
}'
result <- POST("https://weather.magiclaneapis.com/v1/WeatherRoute", body = body,
add_headers(.headers = c("Content-Type"="application/json", "Authorization"="YOUR_API_KEY_TOKEN")))
toJSON(content(result), pretty = TRUE)
To exit the R environment, type q()
The ruby code shown can be saved in a text file such as 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
Then 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,unix_timestamp_seconds coordinate pairs - the weather will be returned for each one separately; details
- 0 returns weather description and temperature (default), 1 - returns all available weather parameters.
require "json"
require "uri"
require "net/http"
require "openssl"
url = URI("https://weather.magiclaneapis.com/v1/WeatherRoute")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Post.new(url)
request["Content-Type"] = "application/json"
request["Accept-Encoding"] = "text"
request["Authorization"] = "YOUR_API_KEY_TOKEN"
request.body =
{
"coords": "43.0, 2.0, 1699512512; 42.6, 2.5, 1699512712; 42.3, 3.111, 1699512912",
"details": 0
}.to_json
puts "sent"
response = http.request(request)
puts response.read_body
Save the following in a text file named Cargo.toml
(case-sensitive). This contains the configuration and dependencies required for compilation.
[package]
name = "restpost"
version = "0.1.0"
edition = "2018"
[[bin]]
name = "weather"
path = "weather.rs"
[dependencies]
json = { version = "0.12.4" }
reqwest = { version = "0.11.18", features = ["json", "blocking"] }
serde_json = { version = "1.0.44" }
tokio = { version = "1.28.2", features = ["macros", "full"] }
weather request with all default values shown explicitly ; coords
, one or more semicolon ; separated latitude,longitude,unix_timestamp_seconds coordinate pairs - the weather will be returned for each one separately; 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
extern crate reqwest;
#[tokio::main]
async fn main() -> Result<(), reqwest::Error>
{
let response = reqwest::Client::new()
.post("https://weather.magiclaneapis.com/v1/WeatherRoute")
.header("Authorization", "YOUR_API_KEY_TOKEN")
.header("Content-Type", "application/json")
.header("Accept-Encoding", "text")
.json(&serde_json::json!({
"coords": "43.0, 2.0, 1699512512; 42.6, 2.5, 1699512712; 42.3, 3.111, 1699512912",
"details": 0
}))
.send().await?;
println!("{:?}",response.text().await?);
Ok(())
}
In Linux (debian/ubuntu flavors), for example, if rust is not installed, it can be installed at the terminal commandline like this:
sudo apt install cargo rustc
Compile the program like this at the commandline, in the directory containing both Cargo.toml
and weather.rs
:
cargo b
To run the program, go to the build directory like this:
cd target/debug
and then run the weather program:
./weather
The Matlab code shown can be copied and pasted into Matlab, without the line numbers - those are for reference.
complete weather request in Matlab
with all default values shown explicitly - coords
, one or more semicolon ; separated latitude,longitude,unix_timestamp_seconds coordinate pairs - the weather will be returned for each one separately; details
- 0 returns weather description and temperature (default), 1 - returns all available weather parameters.
method = matlab.net.http.RequestMethod.POST
f0 = matlab.net.http.HeaderField('Content-Type','application/json')
f1 = matlab.net.http.HeaderField('Authorization','')
header = [f0 f1]
str = [ ...
'{', ...
+ '"coords": "43.0, 2.0, 1699512512; 42.6, 2.5, 1699512712; 42.3, 3.111, 1699512912",', ...
+ '"details": 0,', ...
+ '}' ]
request = matlab.net.http.RequestMessage( method, header, jsondecode(str) );
response = request.send( 'https://weather.magiclaneapis.com/v1/WeatherRoute' );
jsonencode(response.Body.Data,"PrettyPrint",true)
The above code can also be saved in a text file named 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.
The scilab code shown can be copied and pasted into scilab, without the line numbers - those are for reference.
https://www.scilab.org/ Scilab can be downloaded from here
complete weather request in scilab
with all default values shown explicitly - coords
, one or more semicolon ; separated latitude,longitude,unix_timestamp_seconds coordinate pairs - the weather will be returned for each one separately; 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)
jsondata = ...
"{" ...
+"coords: 43.0, 2.0, 1699512512; 42.6, 2.5, 1699512712; 42.3, 3.111, 1699512912," ...
+"details: 0," ...
+"}"
[result, status] = http_post("https://weather.magiclaneapis.com/v1/WeatherRoute", toJSON(fromJSON(jsondata)), format="json", auth="YOUR_API_KEY_TOKEN" );
toJSON(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)
curl "https://weather.magiclaneapis.com/v1/WeatherRoute" -X POST -H "Content-Type: application/json" -H "Authorization: YOUR_API_KEY_TOKEN" -d \
'{
...
}'
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: application/json
key | value |
---|---|
coords (mandatory parameter) | A list of ; (semicolon) separated latitude,longitude,unix_timestamp_seconds coordinate pairs - the weather will be returned for each separately. Example: “43,2,1699512512;42.6,2.5,1699512712;42.3,3.1,1699512912” Note that the unix timestamp, which is the number of seconds elapsed since 1 January 1970 at 00:00, must be in the present or future, as historical weather data is not available. Type: string |
details | Type: integer Default value: 0 Possible values - 0:returns weather description and temperature; 1:returns all available weather parameters |
RESPONSE
WeatherRoute results
Each result item is given in a JSON block as shown below.
In the above examples, 3 coordinate pairs were requested, so the result shows the weather for each of the 3 locations specified along the route at the indicated times. 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.
- Example
- Schema
{
"Weather route": [
{
"WeatherConditions": "Light rain",
"date": 1699512512,
"daylight": "day",
"latitude": 43,
"longitude": 2,
"parameters": {
"DewPoint": 2,
"FeelsLike": 7,
"Humidity": 75,
"Pressure": 1015,
"Temperature": 8,
"UV": 0,
"WindDirection": 90,
"WindSpeed": 2
}
},
{
"WeatherConditions": "Cloudy",
"date": 1699512712,
"daylight": "day",
"latitude": 42.6,
"longitude": 2.5,
"parameters": {
"DewPoint": 1,
"FeelsLike": 7,
"Humidity": 67,
"Pressure": 1013,
"Temperature": 7,
"UV": 0,
"WindDirection": 112,
"WindSpeed": 2
}
},
{
"WeatherConditions": "Cloudy",
"date": 1699512912,
"daylight": "day",
"latitude": 42.3,
"longitude": 3.1,
"parameters": {
"DewPoint": 6,
"FeelsLike": 11,
"Humidity": 65,
"Pressure": 1013,
"Temperature": 11,
"UV": 0,
"WindDirection": 78,
"WindSpeed": 4
}
}
],
"info": {
"copyrights": [
"MagicLane"
]
},
"unit": "metric"
}
Response body schema: application/json
key | value |
---|---|
WeatherConditions | string example: Clear |
date | integer (uint64) example: 1699512512 UNIX timestamp (seconds after 1 January 1970) |
daylight | stringexample: day |
latitude | float (real number) example: 45.95334 |
longitude | float (real number) example: 25.65334 |
parameters { | |
DewPoint | integer example: 10 degrees Celsius |
FeelsLike | integer example: 15 degrees Celsius |
Humidity | integer example: 50 |
Pressure | integer example: 1010 millibars |
Temperature | integer example: 14 degrees Celsius |
UV | integer UV index (0-12) |
WindDirection | integer degrees: 0=North, 90=East, 180=South, 270=West |
WindSpeed | integer integer |