### Fetch Online Controllers using Java Source: https://vatsim.dev/api/core-api/atc-api-online-atc This Java example uses the Apache HttpClient library to make a GET request to the VATSIM API for online controllers. It retrieves and prints the JSON response. ```java import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; public class VatsimApiClient { public static void main(String[] args) { try (CloseableHttpClient client = HttpClients.createDefault()) { HttpGet request = new HttpGet("https://api.vatsim.net/v2/atc/online"); request.addHeader("Accept", "application/json"); try (CloseableHttpResponse response = client.execute(request)) { if (response.getStatusLine().getStatusCode() == 200) { String jsonResponse = EntityUtils.toString(response.getEntity()); System.out.println(jsonResponse); } else { System.err.println("Error: " + response.getStatusLine().getStatusCode()); } } } catch (Exception e) { e.printStackTrace(); } } } ``` -------------------------------- ### Fetch Online Controllers using C# Source: https://vatsim.dev/api/core-api/atc-api-online-atc This C# example uses HttpClient to make a GET request to the VATSIM API for online controllers. It deserializes the JSON response into a list of dynamic objects. ```csharp using System; using System.Net.Http; using System.Threading.Tasks; public class VatsimApiClient { public static async Task Main(string[] args) { using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); string url = "https://api.vatsim.net/v2/atc/online"; try { HttpResponseMessage response = await client.GetAsync(url); response.EnsureSuccessStatusCode(); // Throw if HTTP status code is not 2xx string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } catch (HttpRequestException e) { Console.WriteLine($"Request error: {e.Message}"); } } } } ``` -------------------------------- ### Fetch Online Controllers using Node.js Source: https://vatsim.dev/api/core-api/atc-api-online-atc This Node.js example uses the 'axios' library to fetch the list of online controllers from the VATSIM API. It makes a GET request and logs the JSON response. ```javascript const axios = require('axios'); const url = 'https://api.vatsim.net/v2/atc/online'; axios.get(url, { headers: { 'Accept': 'application/json' } }) .then(response => { console.log(response.data); }) .catch(error => { console.error(`Error fetching data: ${error}`); }); ``` -------------------------------- ### Fetch Online Controllers using cURL Source: https://vatsim.dev/api/core-api/atc-api-online-atc This example shows how to use cURL to make a GET request to the VATSIM API to list online controllers. It includes the necessary headers to accept JSON responses. ```curl curl -L -X GET 'https://api.vatsim.net/v2/atc/online' \ -H 'Accept: application/json' ``` -------------------------------- ### Get Member Status (Go) Source: https://vatsim.dev/api/core-api/members-api-retrieve-member-status Go example demonstrating how to retrieve a VATSIM member's online status using the 'net/http' package. It includes basic error handling for network issues and non-200 status codes. ```Go package main import ( "encoding/json" "fmt" "io/ioutil" "log" "net/http" ) func main() { memberID := "1234567" // Replace with actual member ID url := fmt.Sprintf("https://api.vatsim.net/v2/members/%s/status", memberID) resp, err := http.Get(url) if err != nil { log.Fatalf("Error making request: %v", err) } defer resp.Body.Close() if resp.StatusCode == http.StatusOK { body, err := ioutil.ReadAll(resp.Body) if err != nil { log.Fatalf("Error reading response body: %v", err) } var memberStatus map[string]interface{} if err := json.Unmarshal(body, &memberStatus); err != nil { log.Fatalf("Error unmarshalling JSON: %v", err) } fmt.Printf("Member %s is online:\n%v\n", memberID, memberStatus) } else if resp.StatusCode == http.StatusNotFound { fmt.Printf("Member %s not found or is offline.\n", memberID) } else { log.Fatalf("Unexpected status code: %d", resp.StatusCode) } } ``` -------------------------------- ### Get Member Status (C#) Source: https://vatsim.dev/api/core-api/members-api-retrieve-member-status C# example using HttpClient to retrieve a VATSIM member's online status. It includes handling for successful JSON responses and error conditions like 404 Not Found. ```C# using System; using System.Net.Http; using System.Threading.Tasks; public class VatsimStatusChecker { public static async Task Main(string[] args) { string memberId = "1234567"; // Replace with actual member ID string url = $"https://api.vatsim.net/v2/members/{memberId}/status"; using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); try { HttpResponseMessage response = await client.GetAsync(url); if (response.IsSuccessStatusCode) { string jsonResponse = await response.Content.ReadAsStringAsync(); Console.WriteLine($"Member {memberId} is online:"); Console.WriteLine(jsonResponse); } else if (response.StatusCode == System.Net.HttpStatusCode.NotFound) { Console.WriteLine($"Member {memberId} not found or is offline."); } else { Console.WriteLine($"Unexpected status code: {response.StatusCode}"); string errorResponse = await response.Content.ReadAsStringAsync(); Console.WriteLine($"Error details: {errorResponse}"); } } catch (HttpRequestException e) { Console.WriteLine($"Request error: {e.Message}"); } } } } ``` -------------------------------- ### Get Member Status (Python) Source: https://vatsim.dev/api/core-api/members-api-retrieve-member-status Python example using the 'requests' library to get a member's online status from the VATSIM API. It handles both successful responses (200 OK) and not found errors (404). ```Python import requests member_id = "1234567" # Replace with actual member ID url = f"https://api.vatsim.net/v2/members/{member_id}/status" headers = { "Accept": "application/json" } try: response = requests.get(url, headers=headers) response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx) member_status = response.json() print(f"Member {member_id} is online:") print(member_status) except requests.exceptions.HTTPError as err: if response.status_code == 404: print(f"Member {member_id} not found or is offline.") else: print(f"HTTP error occurred: {err}") except Exception as err: print(f"An error occurred: {err}") ``` -------------------------------- ### Get Member Status (Node.js) Source: https://vatsim.dev/api/core-api/members-api-retrieve-member-status Node.js example using the 'axios' library to fetch a member's online status from the VATSIM API. It demonstrates how to handle successful responses and potential errors, including 404 Not Found. ```Node.js const axios = require('axios'); const memberId = '1234567'; // Replace with actual member ID const url = `https://api.vatsim.net/v2/members/${memberId}/status`; const headers = { 'Accept': 'application/json' }; axios.get(url, { headers }) .then(response => { console.log(`Member ${memberId} is online:`); console.log(response.data); }) .catch(error => { if (error.response) { if (error.response.status === 404) { console.log(`Member ${memberId} not found or is offline.`); } else { console.error(`Error response: ${error.response.status} - ${error.response.data}`); } } else if (error.request) { console.error('No response received:', error.request); } else { console.error('Error setting up request:', error.message); } }); ``` -------------------------------- ### Get Member Status (Java) Source: https://vatsim.dev/api/core-api/members-api-retrieve-member-status Java example using Apache HttpClient to make a GET request to the VATSIM API for member status. It includes error handling for HTTP status codes and JSON parsing. ```Java import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import java.io.IOException; public class VatsimStatusChecker { public static void main(String[] args) { String memberId = "1234567"; // Replace with actual member ID String url = String.format("https://api.vatsim.net/v2/members/%s/status", memberId); try (CloseableHttpClient httpClient = HttpClients.createDefault()) { HttpGet request = new HttpGet(url); request.addHeader("Accept", "application/json"); try (CloseableHttpResponse response = httpClient.execute(request)) { int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 200) { String jsonResponse = EntityUtils.toString(response.getEntity()); System.out.println("Member " + memberId + " is online:"); System.out.println(jsonResponse); } else if (statusCode == 404) { System.out.println("Member " + memberId + " not found or is offline."); } else { System.err.println("Unexpected status code: " + statusCode); String errorResponse = EntityUtils.toString(response.getEntity()); System.err.println("Error details: " + errorResponse); } } } catch (IOException e) { e.printStackTrace(); } } } ``` -------------------------------- ### Fetch VATSIM Member Statistics using Go Source: https://vatsim.dev/api/core-api/members-api-retrieve-member-stats Example Go program to retrieve VATSIM member statistics. It shows how to make an HTTP GET request and unmarshal the JSON response into a Go struct. Error handling for the request and JSON parsing is included. ```go package main import ( "encoding/json" "fmt" "io/ioutil" "net/http" ) func main() { memberID := "YOUR_MEMBER_ID" url := fmt.Sprintf("https://api.vatsim.net/v2/members/%s/stats", memberID) resp, err := http.Get(url) if err != nil { fmt.Printf("Error making request: %s\n", err) return } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Printf("Error reading response body: %s\n", err) return } if resp.StatusCode == http.StatusOK { var stats map[string]interface{}/ err = json.Unmarshal(body, &stats) if err != nil { fmt.Printf("Error unmarshalling JSON: %s\n", err) return } fmt.Println(stats) } else { fmt.Printf("Error: %d %s\n", resp.StatusCode, string(body)) } } ``` -------------------------------- ### Get Member Status (Ruby) Source: https://vatsim.dev/api/core-api/members-api-retrieve-member-status Ruby example using the 'net/http' and 'json' gems to fetch a member's online status from the VATSIM API. It handles successful responses and checks for a 404 status code. ```Ruby require 'net/http' require 'uri' require 'json' member_id = '1234567' # Replace with actual member ID uri = URI.parse("https://api.vatsim.net/v2/members/#{member_id}/status") response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http| request = Net::HTTP::Get.new(uri) request['Accept'] = 'application/json' http.request(request) end case response when Net::HTTPSuccess then member_status = JSON.parse(response.body) puts "Member #{member_id} is online:" puts member_status.inspect when Net::HTTPNotFound then puts "Member #{member_id} not found or is offline." else puts "Unexpected response: #{response.code} #{response.message}" end ``` -------------------------------- ### Fetch VATSIM Member Statistics using Java Source: https://vatsim.dev/api/core-api/members-api-retrieve-member-stats Example Java code using `HttpClient` (available from Java 11+) to retrieve VATSIM member statistics. This demonstrates making an HTTP GET request and parsing the JSON response. Error handling for the request is included. ```java import java.io.IOException; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.time.Duration; public class VatsimStatsFetcher { public static void main(String[] args) { String memberId = "YOUR_MEMBER_ID"; String url = String.format("https://api.vatsim.net/v2/members/%s/stats", memberId); HttpClient client = HttpClient.newBuilder() .version(HttpClient.Version.HTTP_2) .connectTimeout(Duration.ofSeconds(10)) .build(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(url)) .header("Accept", "application/json") .timeout(Duration.ofSeconds(10)) .GET() .build(); try { HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); if (response.statusCode() == 200) { System.out.println(response.body()); // You can parse the JSON response body here using a library like Jackson or Gson } else { System.err.println("Error: " + response.statusCode() + "\n" + response.body()); } } catch (IOException | InterruptedException e) { e.printStackTrace(); } } } ``` -------------------------------- ### GET /v3/all-servers.json Source: https://vatsim.dev/api/data-api/list-all-fsd-servers Retrieves a list of all FSD servers available on the VATSIM network. ```APIDOC ## GET https://data.vatsim.net/v3/all-servers.json ### Description Returns a list of all FSD servers currently configured in the VATSIM network. ### Method GET ### Endpoint https://data.vatsim.net/v3/all-servers.json ### Parameters None ### Response #### Success Response (200) - **ident** (string) - Server identifier - **hostname_or_ip** (string) - Server hostname or IP address - **location** (string) - Human-readable geographical location - **name** (string) - Human-readable name of the server - **client_connections_allowed** (boolean) - Whether the server is accepting connections - **is_sweatbox** (boolean) - Whether the server is in sweatbox mode #### Response Example [ { "ident": "USA-EAST", "hostname_or_ip": "192.0.2.10", "location": "New York, USA", "name": "USA-EAST", "client_connections_allowed": true, "is_sweatbox": false } ] ``` -------------------------------- ### Fetch VATSIM Member Statistics using Node.js Source: https://vatsim.dev/api/core-api/members-api-retrieve-member-stats Example Node.js script using the built-in `https` module to fetch VATSIM member statistics. This demonstrates making an HTTP GET request and handling the response stream, parsing it as JSON. ```javascript const https = require('https'); const memberId = 'YOUR_MEMBER_ID'; const url = `https://api.vatsim.net/v2/members/${memberId}/stats`; const options = { method: 'GET', headers: { 'Accept': 'application/json' } }; const req = https.request(url, options, (res) => { let data = ''; res.on('data', (chunk) => { data += chunk; }); res.on('end', () => { if (res.statusCode === 200) { const stats = JSON.parse(data); console.log(stats); } else { console.error(`Error: ${res.statusCode}`); console.error(data); } }); }); req.on('error', (error) => { console.error(`Request error: ${error}`); }); req.end(); ``` -------------------------------- ### VATSIM OAuth2 Example Error Response (Invalid Client) Source: https://vatsim.dev/api/connect-api/redirect An example JSON object illustrating an error response when the client authentication fails during the VATSIM OAuth2 flow. This response includes the error code, a specific description, and a deprecated message field. ```json { "error": "invalid_client", "error_description": "Client authentication failed", "message": "Client authentication failed" } ``` -------------------------------- ### List Subdivision Members (Node.js) Source: https://vatsim.dev/api/core-api/orgs-api-subdivision-roster This Node.js example fetches subdivision members using the 'axios' library. It sends a GET request to the VATSIM API, providing the API key in the request headers. The subdivision ID is part of the URL, and query parameters can be appended for filtering. ```javascript const axios = require('axios'); const apiKey = ""; const subdivisionId = "YOUR_SUBDIVISION_ID"; const headers = { "Accept": "application/json", "X-API-Key": apiKey }; const url = `https://api.vatsim.net/v2/orgs/subdivision/${subdivisionId}`; axios.get(url, { headers: headers }) .then(response => { console.log(response.data); }) .catch(error => { console.error(`Error: ${error.response.status}`); console.error(error.response.data); }); ``` -------------------------------- ### Fetch VATSIM Member Statistics using C# Source: https://vatsim.dev/api/core-api/members-api-retrieve-member-stats Example C# code using `HttpClient` to retrieve VATSIM member statistics. This demonstrates making an asynchronous GET request and deserializing the JSON response into a C# object. Error handling is included. ```csharp using System; using System.Net.Http; using System.Threading.Tasks; public class VatsimStats { public static async Task GetMemberStats(string memberId) { using (var client = new HttpClient()) { client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); var url = $"https://api.vatsim.net/v2/members/{memberId}/stats"; try { HttpResponseMessage response = await client.GetAsync(url); response.EnsureSuccessStatusCode(); // Throw if not 2xx var jsonResponse = await response.Content.ReadAsStringAsync(); Console.WriteLine(jsonResponse); // You can deserialize jsonResponse into a specific C# object here } catch (HttpRequestException e) { Console.WriteLine($"Request error: {e.Message}"); } } } // Example usage: // public static async Task Main(string[] args) // { // await GetMemberStats("YOUR_MEMBER_ID"); // } } ``` -------------------------------- ### Fetch VATSIM Member Statistics using CURL Source: https://vatsim.dev/api/core-api/members-api-retrieve-member-stats Example using cURL to make a GET request to the VATSIM API to retrieve a member's statistics. This command-line tool is useful for testing API endpoints and understanding the request structure. ```curl curl -L -X GET 'https://api.vatsim.net/v2/members/:member_id/stats' \ -H 'Accept: application/json' ``` -------------------------------- ### Fetch VATSIM Member Statistics using Ruby Source: https://vatsim.dev/api/core-api/members-api-retrieve-member-stats Example Ruby script using the `net/http` library to fetch VATSIM member statistics. This code makes a GET request to the API and parses the JSON response. It includes basic error handling for the HTTP request. ```ruby require 'net/http' require 'uri' require 'json' member_id = 'YOUR_MEMBER_ID' uri = URI.parse("https://api.vatsim.net/v2/members/#{member_id}/stats") http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true request = Net::HTTP::Get.new(uri.request_uri) request['Accept'] = 'application/json' response = http.request(request) if response.code == '200' stats = JSON.parse(response.body) puts stats else puts "Error: #{response.code} - #{response.body}" end ``` -------------------------------- ### GET /v2/atc/online Source: https://vatsim.dev/api/core-api/atc-api-online-atc Retrieves a comprehensive list of all controllers currently connected to the VATSIM network. ```APIDOC ## GET https://api.vatsim.net/v2/atc/online ### Description Returns a list of all online controllers currently active on the VATSIM network. ### Method GET ### Endpoint https://api.vatsim.net/v2/atc/online ### Parameters None ### Request Example ```bash curl -L -X GET 'https://api.vatsim.net/v2/atc/online' \ -H 'Accept: application/json' ``` ### Response #### Success Response (200) - **id** (integer) - Unique controller ID - **callsign** (string) - Station callsign - **start** (date-time) - Connection start time - **server** (string) - Server name - **rating** (integer) - Controller rating - **fp** (object) - Associated flight plan details #### Response Example [ { "id": 0, "callsign": "string", "start": "2025-03-17T15:24:21.986Z", "server": "string", "rating": 0, "fp": { "id": 0, "connection_id": 0, "vatsim_id": "string", "flight_type": "string", "callsign": "string", "aircraft": "string", "cruisespeed": "string", "dep": "string", "arr": "string", "alt": "string", "altitude": "string", "rmks": "string", "route": "string", "deptime": "string", "hrsenroute": 0, "minenroute": 0, "hrsfuel": 0, "minsfuel": 0, "filed": "2025-03-17T15:24:21.986Z", "assignedsquawk": "string", "modifiedbycid": "string", "modifiedbycallsign": "string" } } ] ``` -------------------------------- ### Initiate VATSIM OAuth2 Authorization (Go) Source: https://vatsim.dev/api/connect-api/redirect This Go code snippet shows how to initiate the VATSIM OAuth2 authorization flow. It constructs the authorization URL with query parameters and uses the net/http package to make the request, which will typically result in a redirect. ```go package main import ( "fmt" "net/http" "net/url" ) func main() { baseURL := "https://auth.vatsim.net/oauth/authorize" params := url.Values{} params.Add("response_type", "code") params.Add("client_id", "YOUR_CLIENT_ID") params.Add("redirect_uri", "YOUR_REDIRECT_URI") params.Add("scope", "full_name email vatsim_details country") params.Add("state", "YOUR_STATE_VALUE") params.Add("prompt", "none") finalURL := baseURL + "?" + params.Encode() fmt.Println("Authorization URL:", finalURL) // In a real application, you would redirect the user's browser to finalURL // resp, err := http.Get(finalURL) // Handle response and error } ``` -------------------------------- ### Get Member Status (cURL) Source: https://vatsim.dev/api/core-api/members-api-retrieve-member-status Example using cURL to make a GET request to the VATSIM API to fetch a member's online status. The Accept header is set to application/json to ensure the response is in JSON format. ```cURL curl -L -X GET 'https://api.vatsim.net/v2/members/:member_id/status' \ -H 'Accept: application/json' ``` -------------------------------- ### Request VATSIM Access Token (C#) Source: https://vatsim.dev/api/connect-api/get-token C# code example using HttpClient to request an access token from the VATSIM API. This demonstrates setting up the POST request with form data and appropriate headers. ```csharp using System; using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; public class VatsimAuth { public static async Task RequestTokenAsync() { using (var client = new HttpClient()) { var url = "https://auth.vatsim.net/oauth/token"; var requestContent = new FormUrlEncodedContent(new Dictionary { { "grant_type", "authorization_code" }, // or "password", "refresh_token" { "client_id", "YOUR_CLIENT_ID" }, { "client_secret", "YOUR_CLIENT_SECRET" } // Add other required parameters based on grant_type }); client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); try { var response = await client.PostAsync(url, requestContent); response.EnsureSuccessStatusCode(); // Throw if not 2xx var responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine(responseBody); } catch (HttpRequestException e) { Console.WriteLine($"Request error: {e.Message}"); } } } // Example usage: // public static async Task Main(string[] args) // { // await RequestTokenAsync(); // } } ``` -------------------------------- ### Fetch Online Controllers using Go Source: https://vatsim.dev/api/core-api/atc-api-online-atc This Go program demonstrates how to make an HTTP GET request to the VATSIM API to retrieve online controller data. It uses the standard 'net/http' package and decodes the JSON response. ```go package main import ( "encoding/json" "fmt" "log" "net/http" ) func main() { url := "https://api.vatsim.net/v2/atc/online" resp, err := http.Get(url) if err != nil { log.Fatalf("Error making request: %v", err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { log.Fatalf("Error: received non-200 status code %d", resp.StatusCode) } var data []map[string]interface{}/ if err := json.NewDecoder(resp.Body).Decode(&data); err != nil { log.Fatalf("Error decoding JSON: %v", err) } fmt.Println(data) } ``` -------------------------------- ### Initiate VATSIM OAuth2 Authorization (C#) Source: https://vatsim.dev/api/connect-api/redirect This C# code snippet demonstrates how to construct the VATSIM OAuth2 authorization URL. It uses System.UriBuilder to append the necessary query parameters, enabling the redirection of the user to the VATSIM authentication server. ```csharp using System; using System.Collections.Generic; using System.Web; public class OAuthHelper { public static string BuildAuthUrl() { var baseUrl = "https://auth.vatsim.net/oauth/authorize"; var query = HttpUtility.ParseQueryString(string.Empty); query["response_type"] = "code"; query["client_id"] = "YOUR_CLIENT_ID"; query["redirect_uri"] = "YOUR_REDIRECT_URI"; query["scope"] = "full_name email vatsim_details country"; query["state"] = "YOUR_STATE_VALUE"; query["prompt"] = "none"; var uriBuilder = new UriBuilder(baseUrl) { Query = query.ToString() }; return uriBuilder.ToString(); } public static void Main(string[] args) { string authUrl = BuildAuthUrl(); Console.WriteLine("Authorization URL: " + authUrl); // In a web application, you would redirect the user's browser to this URL. } } ``` -------------------------------- ### Get Member Status (PHP) Source: https://vatsim.dev/api/core-api/members-api-retrieve-member-status PHP example using cURL to fetch a member's online status from the VATSIM API. It checks the HTTP status code and processes the JSON response or indicates if the member is not found. ```PHP ``` -------------------------------- ### VATSIM API Overview Source: https://vatsim.dev/api/core-api General introduction to the VATSIM RESTful API structure and available data categories. ```APIDOC ## VATSIM Core API ### Description The VATSIM API is a RESTful service providing access to network-wide data. It is organized into several key resource categories including members, community, organizations, and ATC. ### Base URL https://api.vatsim.net/v2 ### Resource Categories - **members**: Access to user-related data (8 items). - **community**: Access to community-related data (1 item). - **orgs**: Access to organizational data (2 items). - **atc**: Access to Air Traffic Control data (2 items). ``` -------------------------------- ### Request VATSIM Access Token (Go) Source: https://vatsim.dev/api/connect-api/get-token Go program to request an access token from the VATSIM API. It demonstrates using the 'net/http' package to send a POST request with form data. ```go package main import ( "fmt" "net/http" "net/url" "strings" ) func main() { url := "https://auth.vatsim.net/oauth/token" payload := url.Values{} payload.Set("grant_type", "authorization_code") // or "password", "refresh_token" payload.Set("client_id", "YOUR_CLIENT_ID") payload.Set("client_secret", "YOUR_CLIENT_SECRET") // Add other required parameters based on grant_type req, err := http.NewRequest("POST", url, strings.NewReader(payload.Encode())) if err != nil { fmt.Printf("Error creating request: %s\n", err) return } req.Header.Add("Content-Type", "application/x-www-form-urlencoded") req.Header.Add("Accept", "application/json") client := &http.Client{} res, err := client.Do(req) if err != nil { fmt.Printf("Error sending request: %s\n", err) return } defer res.Body.Close() fmt.Printf("Status Code: %d\n", res.StatusCode) // Read and process response body here } ``` -------------------------------- ### Initiate VATSIM OAuth2 Authorization (Node.js) Source: https://vatsim.dev/api/connect-api/redirect This Node.js code snippet demonstrates initiating the VATSIM OAuth2 authorization flow using the 'axios' library. It constructs the authorization URL with the necessary query parameters to redirect the user to the VATSIM authentication server. ```nodejs const axios = require('axios'); const authUrl = 'https://auth.vatsim.net/oauth/authorize'; const params = { response_type: 'code', client_id: 'YOUR_CLIENT_ID', redirect_uri: 'YOUR_REDIRECT_URI', scope: 'full_name email vatsim_details country', state: 'YOUR_STATE_VALUE', prompt: 'none' }; // Construct the full URL with query parameters const queryString = new URLSearchParams(params).toString(); const finalUrl = `${authUrl}?${queryString}`; console.log('Authorization URL:', finalUrl); // In a real Node.js application, you would typically redirect the user's browser // For example, using Express.js: // app.get('/login', (req, res) => { // res.redirect(finalUrl); // }); ``` -------------------------------- ### Initiate VATSIM OAuth2 Authorization (Python) Source: https://vatsim.dev/api/connect-api/redirect This Python code snippet demonstrates how to initiate the VATSIM OAuth2 authorization flow using the requests library. It constructs the authorization URL with necessary query parameters to redirect the user to the VATSIM authentication server. ```python import requests auth_url = "https://auth.vatsim.net/oauth/authorize" params = { "response_type": "code", "client_id": "YOUR_CLIENT_ID", "redirect_uri": "YOUR_REDIRECT_URI", "scope": "full_name email vatsim_details country", "state": "YOUR_STATE_VALUE", "prompt": "none" } response = requests.get(auth_url, params=params) print(f"Redirect URL: {response.url}") ``` -------------------------------- ### Fetch VATSIM Member Statistics using PowerShell Source: https://vatsim.dev/api/core-api/members-api-retrieve-member-stats Example PowerShell script to retrieve VATSIM member statistics using `Invoke-RestMethod`. This command makes a GET request to the API and automatically parses the JSON response. Error handling for the request is included. ```powershell $memberId = "YOUR_MEMBER_ID" $url = "https://api.vatsim.net/v2/members/$memberId/stats" $headers = @{ "Accept" = "application/json" } try { $stats = Invoke-RestMethod -Uri $url -Method Get -Headers $headers Write-Host $stats } catch { Write-Error "Error: $($_.Exception.Message)" if ($_.Exception.Response) { $stream = $_.Exception.Response.GetResponseStream() $reader = New-Object System.IO.StreamReader($stream) Write-Error $reader.ReadToEnd() } } ``` -------------------------------- ### Fetch VATSIM Member Statistics using PHP Source: https://vatsim.dev/api/core-api/members-api-retrieve-member-stats Example PHP script using cURL to fetch VATSIM member statistics. This code makes a GET request to the API and processes the JSON response. It includes error checking for the cURL request and response. ```php ``` -------------------------------- ### Initiate VATSIM OAuth2 Authorization (Java) Source: https://vatsim.dev/api/connect-api/redirect This Java code snippet demonstrates constructing the VATSIM OAuth2 authorization URL. It uses Java's built-in URI and URLEncoder classes to properly format the query parameters for redirecting the user to the VATSIM authentication server. ```java import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; public class OAuthHelper { public static String buildAuthUrl() { String baseUrl = "https://auth.vatsim.net/oauth/authorize"; Map params = new HashMap<>(); params.put("response_type", "code"); params.put("client_id", "YOUR_CLIENT_ID"); params.put("redirect_uri", "YOUR_REDIRECT_URI"); params.put("scope", "full_name email vatsim_details country"); params.put("state", "YOUR_STATE_VALUE"); params.put("prompt", "none"); StringBuilder query = new StringBuilder(); try { for (Map.Entry entry : params.entrySet()) { if (query.length() > 0) { query.append("&"); } query.append(URLEncoder.encode(entry.getKey(), "UTF-8")); query.append("="); query.append(URLEncoder.encode(entry.getValue(), "UTF-8")); } } catch (UnsupportedEncodingException e) { // Handle encoding exception e.printStackTrace(); return null; } return baseUrl + "?" + query.toString(); } public static void main(String[] args) { String authUrl = buildAuthUrl(); System.out.println("Authorization URL: " + authUrl); // In a web application, you would redirect the user's browser to this URL. } } ``` -------------------------------- ### Request VATSIM Access Token (Node.js) Source: https://vatsim.dev/api/connect-api/get-token Node.js example using the 'axios' library to request an access token from the VATSIM API. This snippet shows how to configure the request with appropriate headers and body parameters. ```javascript const axios = require('axios'); const url = 'https://auth.vatsim.net/oauth/token'; const headers = { 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json' }; const data = new URLSearchParams({ grant_type: 'authorization_code', // or 'password', 'refresh_token' client_id: 'YOUR_CLIENT_ID', client_secret: 'YOUR_CLIENT_SECRET', // Add other required parameters based on grant_type }); axios.post(url, data, { headers: headers }) .then(response => { console.log(response.data); }) .catch(error => { console.error(`Error: ${error.response.status}`); console.error(error.response.data); }); ``` -------------------------------- ### Fetch Historical ATC Sessions - cURL Source: https://vatsim.dev/api/core-api/atc-api-history-atc Example using cURL to fetch historical ATC session data from the VATSIM API. This command sends a GET request to the specified endpoint and sets the 'Accept' header to 'application/json' to ensure the response is in JSON format. ```cURL curl -L -X GET 'https://api.vatsim.net/v2/atc/history' \ -H 'Accept: application/json' ``` -------------------------------- ### VATSIM Webhook Example: Combined Creation and Update Source: https://vatsim.dev/services/webhooks/structure This JSON object demonstrates a typical VATSIM webhook payload for a combined member creation and update event. It includes details about the resource, the actions performed (creation and change), the authority responsible, and the specific field deltas for each action. The 'deltas' field shows the 'before' and 'after' states of modified fields. ```json { "resource": 1851903, "actions": [ { "action": "member_created_action", "authority": "myVATSIM", "comment": null, "deltas": [ { "field": "id", "before": null, "after": 1851903 }, { "field": "name_first", "before": null, "after": "John" }, { "field": "name_last", "before": null, "after": "Doe" }, { "field": "email", "before": null, "after": "tech@vatsim.net" }, { "field": "rating", "before": null, "after": 1 }, { "field": "pilotrating", "before": null, "after": -1 }, { "field": "susp_date", "before": null, "after": "2022-10-11T12:09:13" }, { "field": "reg_date", "before": null, "after": "2022-10-11T12:09:13" }, { "field": "region_id", "before": null, "after": "AMAS" }, { "field": "division_id", "before": null, "after": "USA" }, { "field": "subdivision_id", "before": null, "after": null }, { "field": "lastratingchange", "before": null, "after": null } ], "timestamp": 1665490153.562588 }, { "action": "member_changed_action", "authority": "VATUSA", "comment": "Promotion to S1", "deltas": [ { "field": "rating", "before": 1, "after": 2 }, { "field": "lastratingchange", "before": null, "after": "2022-10-18T17:19:34" } ], "timestamp": 1666113574.577162 } ] } ``` -------------------------------- ### List Division Members (cURL) Source: https://vatsim.dev/api/core-api/orgs-api-division-roster Example using cURL to fetch a list of active members for a given division ID. Requires an API key for authentication. ```bash curl -L -X GET 'https://api.vatsim.net/v2/orgs/division/:division_id' \ -H 'Accept: application/json' \ -H 'X-API-Key: ' ``` -------------------------------- ### Fetch Online Controllers using Python Source: https://vatsim.dev/api/core-api/atc-api-online-atc This Python script utilizes the 'requests' library to fetch the list of online controllers from the VATSIM API. It handles the GET request and prints the JSON response. ```python import requests url = "https://api.vatsim.net/v2/atc/online" headers = { "Accept": "application/json" } response = requests.get(url, headers=headers) if response.status_code == 200: print(response.json()) else: print(f"Error: {response.status_code}") ``` -------------------------------- ### Get VATSIM Member Statistics (REST API) Source: https://vatsim.dev/api/core-api/members-api-retrieve-member-stats This endpoint retrieves statistics for a given VATSIM member ID. It returns data on their ATC and pilot ratings. The API supports GET requests and returns JSON responses. Common response codes are 200 for success and 404 for not found. ```http GET /v2/members/:member_id/stats ``` -------------------------------- ### Fetch VATSIM Member Statistics using Python Source: https://vatsim.dev/api/core-api/members-api-retrieve-member-stats Example Python script to fetch VATSIM member statistics using the `requests` library. This demonstrates how to construct the API request, handle the response, and parse the JSON output. ```python import requests member_id = "YOUR_MEMBER_ID" url = f"https://api.vatsim.net/v2/members/{member_id}/stats" headers = { "Accept": "application/json" } response = requests.get(url, headers=headers) if response.status_code == 200: stats = response.json() print(stats) else: print(f"Error: {response.status_code}") ``` -------------------------------- ### GET /v3/vatsim-data.json Source: https://vatsim.dev/api/data-api/get-network-data Retrieves the current status and active clients on the VATSIM network. ```APIDOC ## GET /v3/vatsim-data.json ### Description Fetches the full network status, including general stats, active pilots, controllers, ATIS, servers, and pre-filed flight plans. ### Method GET ### Endpoint /v3/vatsim-data.json ### Parameters None ### Request Example curl -X GET "https://data.vatsim.net/v3/vatsim-data.json" ### Response #### Success Response (200) - **general** (object) - System-wide status metadata. - **pilots** (array) - List of currently connected pilots. - **controllers** (array) - List of active ATC controllers. - **atis** (array) - List of active ATIS stations. - **servers** (array) - List of available network servers. - **facilities** (array) - Definitions for facility types. - **ratings** (array) - Definitions for controller ratings. #### Response Example { "general": { "version": 3, "connected_clients": 1 }, "pilots": [ { "cid": 1234567, "name": "Kennedy Steve KJFK", "callsign": "DAL1" } ] } ``` -------------------------------- ### Initiate VATSIM OAuth2 Authorization (PowerShell) Source: https://vatsim.dev/api/connect-api/redirect This PowerShell script constructs the VATSIM OAuth2 authorization URL. It uses a hashtable to define the query parameters and then formats them into a complete URL for redirecting the user to the VATSIM authentication server. ```powershell $baseUrl = "https://auth.vatsim.net/oauth/authorize" $params = @{ "response_type" = "code" "client_id" = "YOUR_CLIENT_ID" "redirect_uri" = "YOUR_REDIRECT_URI" "scope" = "full_name email vatsim_details country" "state" = "YOUR_STATE_VALUE" "prompt" = "none" } $queryString = "" $params.GetEnumerator() | ForEach-Object { $queryString += "$($_.Name)=$($_.Value)&" } # Remove trailing '&' $queryString = $queryString.Substring(0, $queryString.Length - 1) $finalUrl = "$baseUrl?$queryString" Write-Host "Authorization URL: $finalUrl" # In a web application context, you would use something like: # Invoke-WebRequest -Uri $finalUrl -Method Get ``` -------------------------------- ### GET /v3/vatsim-data.json Source: https://vatsim.dev/api/data-api/get-network-data Retrieves the complete live data feed for the VATSIM network. ```APIDOC ## GET /v3/vatsim-data.json ### Description Retrieves the live data feed of the VATSIM network. This data is re-generated every 15 seconds. ### Method GET ### Endpoint https://data.vatsim.net/v3/vatsim-data.json ### Parameters None ### Request Example GET https://data.vatsim.net/v3/vatsim-data.json ### Response #### Success Response (200) - **data** (object) - The full JSON object containing network status, pilots, controllers, and airports. #### Response Example { "general": { ... }, "pilots": [ ... ], "controllers": [ ... ] } ``` -------------------------------- ### GET /api/v2/events/latest Source: https://vatsim.dev/api/events-api/list-all-events Retrieves a list of all current and upcoming events on the VATSIM network. ```APIDOC ## GET https://my.vatsim.net/api/v2/events/latest ### Description Returns a list of all current and upcoming events on the VATSIM network. ### Method GET ### Endpoint https://my.vatsim.net/api/v2/events/latest ### Parameters None ### Response #### Success Response (200) - **data** (array) - List of event objects containing details like id, type, name, organisers, airports, routes, and timing. #### Response Example { "data": [ { "id": 1, "type": "Event", "name": "Example Event", "link": "https://my.vatsim.net/events/example-event", "organisers": [ { "region": "AMAS", "division": "USA", "subdivision": null, "organised_by_vatsim": false } ], "airports": [ { "icao": "KJFK" } ], "routes": [ { "departure": "KJFK", "arrival": "KATL", "route": "RBV Q430 BYRDD J48 MOL FLASK OZZZI1" } ], "start_time": "1970-01-01T00:00:00.000000Z", "end_time": "1970-01-01T06:00:00.000000Z", "short_description": "Fly with us tonight!", "description": "Fly with us tonight!", "banner": "https://vatsim-my.nyc3.digitaloceanspaces.com/events/JpjoYKp6CRcz4V1wvdlMnQHiAtYOmT2p3DevEA7j.png" } ] } ```