### Retrieve Starting Grid Data (R) Source: https://github.com/br-g/openf1/blob/main/documentation/includes/_api_endpoints.md Access starting grid data using R with the `httr` and `jsonlite` packages. This example demonstrates making an HTTP GET request and parsing the JSON response. The commented-out lines show how to convert the data into a data frame. ```r # If needed, install libraries # install.packages('httr') # install.packages('jsonlite') library(httr) library(jsonlite) response <- GET("https://api.openf1.org/v1/starting_grid?session_key=7783&position%3C=3") parsed_data <- fromJSON(content(response, 'text')) print(parsed_data) # If you want, you can import the results in a DataFrame # df <- do.call(rbind, lapply(parsed_data, data.frame, stringsAsFactors = FALSE)) # df <- as.data.frame(t(as.matrix(df))) ``` -------------------------------- ### Retrieve Starting Grid Data (JavaScript) Source: https://github.com/br-g/openf1/blob/main/documentation/includes/_api_endpoints.md Use the `fetch` API in JavaScript to retrieve starting grid data. This example shows how to make the request and log the JSON content to the console. ```javascript fetch("https://api.openf1.org/v1/starting_grid?session_key=7783&position%3C=3") .then((response) => response.json()) .then((jsonContent) => console.log(jsonContent)); ``` -------------------------------- ### Retrieve Starting Grid Data (Python) Source: https://github.com/br-g/openf1/blob/main/documentation/includes/_api_endpoints.md Fetch starting grid data using Python's `urllib.request`. This example shows how to make the request and parse the JSON response. For easier data manipulation, consider using the pandas library. ```python from urllib.request import urlopen import json response = urlopen("https://api.openf1.org/v1/starting_grid?session_key=7783&position%3C=3") data = json.loads(response.read().decode('utf-8')) print(data) # If you want, you can import the results in a DataFrame (you need to install the `pandas` package first) # import pandas as pd # df = pd.DataFrame(data) ``` -------------------------------- ### Retrieve Starting Grid Data (Shell) Source: https://github.com/br-g/openf1/blob/main/documentation/includes/_api_endpoints.md Use this command to fetch starting grid data for a specific session, filtered by position. This is useful for checking the top drivers' starting positions. ```shell curl "https://api.openf1.org/v1/starting_grid?session_key=7783&position%3C=3" ``` -------------------------------- ### Start Live Timing Ingestor Source: https://github.com/br-g/openf1/blob/main/src/openf1/services/ingestor_livetiming/real_time/README.md Run the ingestor service from the command line to capture live timing data. Ensure the recording is started sufficiently before the session begins. ```bash python -m openf1.services.ingestor_livetiming.real_time.app ``` -------------------------------- ### Fetch Race Starting Grid Source: https://context7.com/br-g/openf1/llms.txt Retrieves the starting grid for a session, limited to the top 3 positions. Requires the session key. ```bash # Front three rows of the grid for session 7783 curl "https://api.openf1.org/v1/starting_grid?session_key=7783&position%3C=3" ``` ```javascript fetch("https://api.openf1.org/v1/starting_grid?session_key=7783&position%3C=3") .then(r => r.json()) .then(grid => grid.forEach(g => console.log(`P${g.position}: Driver #${g.driver_number} (${g.lap_duration}s)`) )); ``` -------------------------------- ### Clone OpenF1 Repository and Install Dependencies Source: https://github.com/br-g/openf1/blob/main/README.md Steps to clone the OpenF1 project from GitHub and install the Python package locally. Ensure pip is updated and Python 3.10+ is installed. ```bash git clone git@github.com:br-g/openf1.git pip install -e openf1 ``` -------------------------------- ### Fetch F1 Starting Grid Source: https://github.com/br-g/openf1/blob/main/src/openf1/services/f1_scraping/README.md Fetch the starting grid for a specific F1 session using meeting and session keys. This function is only applicable to qualifying sessions and defaults to the latest session if parameters are not provided. ```bash python -m openf1.services.f1_scraping.starting_grid --meeting-key 1264 --session-key 9951 ``` -------------------------------- ### Fetch Session Results with JavaScript Source: https://github.com/br-g/openf1/blob/main/documentation/includes/_api_endpoints.md Use the fetch API in JavaScript to retrieve session results. This example gets data for a specific session key and filters by position, logging the JSON content to the console. ```javascript fetch("https://api.openf1.org/v1/session_result?session_key=7782&position%3C=3") .then((response) => response.json()) .then((jsonContent) => console.log(jsonContent)); ``` -------------------------------- ### Example JSON message for v1/location topic Source: https://github.com/br-g/openf1/blob/main/documentation/pages/auth.html This is an example of the JSON payload structure received for the 'v1/location' topic, including meeting and session details, driver information, coordinates, and OpenF1 specific fields like '_key' and '_id'. ```json { "meeting_key": 1257, "session_key": 10007, "driver_number": 31, "date": "2025-04-11T11:21:16.603025+00:00", "x": 0, "y": 0, "z": 0, "_key": "1744370476603_31", "_id": 1747235800206 } ``` -------------------------------- ### Starting Grid Source: https://github.com/br-g/openf1/blob/main/documentation/includes/_api_endpoints.md Provides the starting grid for the upcoming race. This data becomes available a few minutes after the official results are published on the official Formula 1 website. ```APIDOC ## GET /v1/starting_grid ### Description Retrieves the starting grid for a given session, optionally filtered by position. ### Method GET ### Endpoint /v1/starting_grid ### Parameters #### Query Parameters - **session_key** (integer) - Required - The unique identifier for the session. - **position** (integer) - Optional - Filters the results to include only drivers at or before the specified position. ### Request Example ```shell curl "https://api.openf1.org/v1/starting_grid?session_key=7783&position%3C=3" ``` ### Response #### Success Response (200) - **position** (integer) - The driver's starting position. - **driver_number** (integer) - The unique number assigned to the driver for the season. - **lap_duration** (float) - The duration of the lap in seconds. - **meeting_key** (integer) - The unique identifier for the meeting. - **session_key** (integer) - The unique identifier for the session. #### Response Example ```json [ { "position": 1, "driver_number": 1, "lap_duration": 76.732, "meeting_key": 1143, "session_key": 7783 } ] ``` ``` -------------------------------- ### GET /v1/starting_grid Source: https://context7.com/br-g/openf1/llms.txt Returns the pre-race grid position and qualifying lap time for each driver. ```APIDOC ## GET /v1/starting_grid — Race starting grid Returns the pre-race grid position and qualifying lap time for each driver. Available a few minutes after official qualifying results are published. ### Parameters #### Query Parameters - **session_key** (integer) - Required - The unique identifier for the session. - **position** (integer) - Optional - Filter results by position (e.g., position<=3 for top 3). ### Request Example ```bash # Front three rows of the grid for session 7783 curl "https://api.openf1.org/v1/starting_grid?session_key=7783&position%3C=3" ``` ### Response #### Success Response (200) - **position** (integer) - The driver's grid position. - **driver_number** (integer) - The driver's unique number. - **lap_duration** (string) - The duration of the driver's qualifying lap. - **meeting_key** (integer) - The unique identifier for the meeting. - **session_key** (integer) - The unique identifier for the session. ``` -------------------------------- ### Make Authenticated GET Request with Python Source: https://github.com/br-g/openf1/blob/main/documentation/pages/auth.html This Python snippet shows how to make an authenticated GET request to the OpenF1 API. It constructs the necessary headers, including the 'Authorization' header with your Bearer token, and sends the request using the `requests` library. Error handling for non-200 status codes is included. ```python import requests # Assume 'access_token' is a variable holding your obtained token access_token = "YOUR_ACCESS_TOKEN" api_url = "https://api.openf1.org/v1/sessions?year=2024" # Example headers = { "accept": "application/json", "Authorization": f"Bearer {access_token}" } response = requests.get(api_url, headers=headers) if response.status_code == 200: data = response.json() print(data) else: print(f"Error fetching data: {response.status_code} - {response.text}") ``` -------------------------------- ### GET /v1/weather Source: https://context7.com/br-g/openf1/llms.txt Returns atmospheric conditions at the circuit, updated every minute during sessions. ```APIDOC ## GET /v1/weather — Track weather data (1-minute updates) Returns atmospheric conditions at the circuit: air temperature, track temperature, humidity, pressure, wind speed/direction, and rainfall indicator. Updated every minute during sessions. ### Parameters #### Query Parameters - **meeting_key** (integer) - Optional - The unique identifier for the meeting. - **wind_direction** (integer) - Optional - Filter by wind direction (e.g., wind_direction>=130). - **track_temperature** (float) - Optional - Filter by track temperature (e.g., track_temperature>=52). ### Request Example ```bash # Hot and windy moments during meeting 1208 (Miami GP) curl "https://api.openf1.org/v1/weather?meeting_key=1208&wind_direction>=130&track_temperature>=52" ``` ### Response #### Success Response (200) - **air_temperature** (float) - The ambient air temperature in Celsius. - **date** (string) - The timestamp of the weather reading. - **humidity** (integer) - The relative humidity in percent. - **meeting_key** (integer) - The unique identifier for the meeting. - **pressure** (float) - The atmospheric pressure in hectopascals (hPa). - **rainfall** (integer) - Indicates if rain is present (0 for no rain, 1 for rain). - **session_key** (integer) - The unique identifier for the session. - **track_temperature** (float) - The track surface temperature in Celsius. - **wind_direction** (integer) - The wind direction in degrees (0-360). - **wind_speed** (float) - The wind speed in meters per second (m/s). ``` -------------------------------- ### Run Query API Locally Source: https://github.com/br-g/openf1/blob/main/src/openf1/services/query_api/README.md Start the OpenF1 Query API service in development mode using uvicorn. This command enables hot-reloading for faster development cycles. ```bash uvicorn openf1.services.query_api.app:app --reload ``` -------------------------------- ### Make Authenticated GET Request with cURL Source: https://github.com/br-g/openf1/blob/main/documentation/pages/auth.html This cURL command demonstrates how to make an authenticated GET request to the OpenF1 API. Replace 'YOUR_ACCESS_TOKEN' with your obtained token and include it in the 'Authorization' header as a Bearer token. ```bash # Replace YOUR_ACCESS_TOKEN with the token you obtained curl -X 'GET' \ 'https://api.openf1.org/v1/sessions?year=2024' \ -H 'accept: application/json' \ -H 'Authorization: Bearer YOUR_ACCESS_TOKEN' ``` -------------------------------- ### Retrieve Stint Data with cURL Source: https://github.com/br-g/openf1/blob/main/documentation/includes/_api_endpoints.md Use this command to fetch stint information from the OpenF1 API. Filter results by session key and tyre age at start. ```shell curl "https://api.openf1.org/v1/stints?session_key=9165&tyre_age_at_start>=3" ``` -------------------------------- ### Fetch Sessions Data using JavaScript Source: https://github.com/br-g/openf1/blob/main/documentation/includes/_api_endpoints.md Use the `fetch` API in JavaScript to get session data. The response is parsed as JSON and logged to the console. ```javascript fetch( "https://api.openf1.org/v1/sessions?country_name=Belgium&session_name=Sprint%20Qualifying&year=2023", ) .then((response) => response.json()) .then((jsonContent) => console.log(jsonContent)); ``` -------------------------------- ### Authenticated API Request Source: https://github.com/br-g/openf1/blob/main/documentation/pages/auth.html Demonstrates how to make authenticated GET requests to the OpenF1 REST API using the obtained access token in the Authorization header. ```APIDOC ## Authenticated API Request ### Description Accesses real-time data by including the access token in the `Authorization` header as a Bearer token. ### Method GET ### Endpoint `https://api.openf1.org/v1/sessions?year=2024` (Example endpoint) ### Parameters #### Headers - **accept** (string) - Required - Specifies the expected response format, typically `application/json`. - **Authorization** (string) - Required - The access token prefixed with `Bearer `. ### Request Example (Bash/cURL) ```bash curl -X 'GET' \ 'https://api.openf1.org/v1/sessions?year=2024' \ -H 'accept: application/json' \ -H 'Authorization: Bearer YOUR_ACCESS_TOKEN' ``` ### Request Example (Python) ```python import requests # Assume 'access_token' is a variable holding your obtained token access_token = "YOUR_ACCESS_TOKEN" api_url = "https://api.openf1.org/v1/sessions?year=2024" # Example headers = { "accept": "application/json", "Authorization": f"Bearer {access_token}" } response = requests.get(api_url, headers=headers) if response.status_code == 200: data = response.json() print(data) else: print(f"Error fetching data: {response.status_code} - {response.text}") ``` ### Request Example (JavaScript) ```javascript async function fetchDataWithToken(accessToken) { const apiUrl = "https://api.openf1.org/v1/sessions?year=2024"; // Example try { const response = await fetch(apiUrl, { method: "GET", headers: { "accept": "application/json", "Authorization": `Bearer ${accessToken}`, }, }); if (response.ok) { const data = await response.json(); console.log(data); return data; } } catch (error) { console.error("Network error or other issue:", error); return null; } } ``` ### Response #### Success Response (200) - The response will be a JSON object containing the requested data. ### Response Example (Response structure depends on the specific API endpoint called.) ``` -------------------------------- ### Get Raw Content of a Topic Source: https://github.com/br-g/openf1/blob/main/src/openf1/services/ingestor_livetiming/historical/README.md Fetches the raw content for a specific topic within a given session. Requires year, meeting, session IDs, and the topic name. ```bash python -m openf1.services.ingestor_livetiming.historical.main get-topic-content 2024 1242 9574 DriverList ``` -------------------------------- ### Fetch Tyre Stint Data Source: https://context7.com/br-g/openf1/llms.txt Retrieves tyre stint data for a session, filtering for stints where tyres had an age of 3 laps or more at the start. Requires the session key. ```bash # All stints with pre-used tyres (age >= 3 laps) in the Singapore race (9165) curl "https://api.openf1.org/v1/stints?session_key=9165&tyre_age_at_start>=3" ``` ```python import json from urllib.request import urlopen stints = json.loads(urlopen( 'https://api.openf1.org/v1/stints?session_key=9165&tyre_age_at_start>=3' ).read().decode('utf-8')) for s in stints: print(f"Driver {s['driver_number']}: {s['compound']} laps {s['lap_start']}–{s['lap_end']}") ``` -------------------------------- ### Fetch Championship Drivers Data (R) Source: https://github.com/br-g/openf1/blob/main/documentation/includes/_api_endpoints.md This R code snippet demonstrates how to fetch championship standings. Uncomment the install.packages line if you need to install the 'httr' library. ```r # If needed, install libraries # install.packages('httr') ``` -------------------------------- ### Connect to OpenF1 via Websockets (MQTT.js) Source: https://github.com/br-g/openf1/blob/main/documentation/pages/auth.html Connect to OpenF1's MQTT broker over WSS using the MQTT.js library. Ensure you have obtained an access token and configure the client with the correct URL and authentication options. Subscribe to desired topics like 'v1/location' or 'v1/laps'. ```javascript // In Node.js: npm install mqtt // In Browser: // Assume 'accessToken' is a variable holding your obtained token const accessToken = "YOUR_ACCESS_TOKEN"; const websocketUrl = "wss://mqtt.openf1.org:8084/mqtt"; const options = { username: "your_username_or_email@example.com", // Optional, can be any string password: accessToken // Access token is used as the password }; const client = mqtt.connect(websocketUrl, options); client.on('connect', function () { console.log('Connected to OpenF1 via Websockets'); client.subscribe('v1/location', function (err) { if (!err) { console.log('Subscribed to v1/location'); } else { console.error('Subscription error for v1/location:', err); } }); client.subscribe('v1/laps', function (err) { if (!err) { console.log('Subscribed to v1/laps'); } else { console.error('Subscription error for v1/laps:', err); } }); // client.subscribe('#'); // Subscribe to all topics }); client.on('message', function (topic, message) { console.log(`Received on ${topic}: ${message.toString()}`); // const data = JSON.parse(message.toString()); // Process data }); client.on('error', function (error) { console.error('MQTT Connection Error:', error); }); client.on('close', function () { console.log('MQTT Connection closed'); }); client.on('offline', function() { console.log('MQTT Client is offline'); }); client.on('reconnect', function() { console.log('MQTT Client is attempting to reconnect'); }); ``` -------------------------------- ### Connect to OpenF1 MQTT Broker with Python Source: https://github.com/br-g/openf1/blob/main/documentation/pages/auth.html Connects to the OpenF1 MQTT broker using the paho-mqtt library. Requires an OAuth2 access token for authentication and TLS for secure communication. Subscribes to 'v1/location' and 'v1/laps' topics. ```python import paho.mqtt.client as mqtt import ssl # Assume 'access_token' is a variable holding your obtained token access_token = "YOUR_ACCESS_TOKEN" mqtt_broker = "mqtt.openf1.org" mqtt_port = 8883 # Optional: Provide a username. Can be an email or any non-empty string. mqtt_username = "your_username_or_email@example.com" def on_connect(client, userdata, flags, rc, properties=None): if rc == 0: print("Connected to OpenF1 MQTT broker") client.subscribe("v1/location") client.subscribe("v1/laps") # client.subscribe("#") # Subscribe to all topics else: print(f"Failed to connect, return code {rc}") def on_message(client, userdata, msg): print(f"Received message on topic '{msg.topic}': {msg.payload.decode()}") # Example: data = json.loads(msg.payload.decode()) client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2) client.username_pw_set(username=mqtt_username, password=access_token) client.tls_set(cert_reqs=ssl.CERT_REQUIRED, tls_version=ssl.PROTOCOL_TLS_CLIENT) client.on_connect = on_connect client.on_message = on_message try: client.connect(mqtt_broker, mqtt_port, 60) client.loop_forever() # Starts a blocking network loop except Exception as e: print(f"Connection error: {e}") ``` -------------------------------- ### Make Authenticated GET Request with JavaScript Source: https://github.com/br-g/openf1/blob/main/documentation/pages/auth.html This JavaScript function uses the Fetch API to make an authenticated GET request. It takes an access token as an argument and includes it in the 'Authorization' header. The function logs the fetched data or any errors encountered during the request. ```javascript async function fetchDataWithToken(accessToken) { const apiUrl = "https://api.openf1.org/v1/sessions?year=2024"; // Example try { const response = await fetch(apiUrl, { method: "GET", headers: { "accept": "application/json", "Authorization": `Bearer ${accessToken}`, }, }); if (response.ok) { const data = await response.json(); console.log(data); return data; } else { console.error("Error fetching data:", response.status, await response.text()); return null; } } catch (error) { console.error("Network error or other issue:", error); return null; } } // Example usage: // getAccessToken().then(token => { // if (token) { // fetchDataWithToken(token); // } // }); ``` -------------------------------- ### List Available Topics for a Session Source: https://github.com/br-g/openf1/blob/main/src/openf1/services/ingestor_livetiming/historical/README.md Lists all available data topics for a specific session, identified by year, meeting, and session IDs. ```bash python -m openf1.services.ingestor_livetiming.historical.main list-topics 2024 1242 9574 ``` -------------------------------- ### Real-time Data Connections Source: https://github.com/br-g/openf1/blob/main/documentation/pages/auth.html Information on connecting to real-time data streams via MQTT and WebSockets, which is the recommended method for live data. ```APIDOC ## Real-time Data Connections ### Description Provides details for connecting to real-time data streams using MQTT and WebSockets, offering a more efficient way to receive data as it becomes available. ### Connection Details * **MQTT server:** `mqtt.openf1.org` * **MQTT port (TLS/MQTTS):** `8883` * **Websockets URL (WSS for MQTT over Websockets):** `wss://mqtt.openf1.org:8084/mqtt` **Recommendation:** This is the preferred method for accessing live data. ``` -------------------------------- ### Get Latest Car Data Source: https://context7.com/br-g/openf1/llms.txt Retrieve car data for the most recent session. ```APIDOC ## GET /v1/car_data ### Description Retrieves real-time car telemetry data for the latest session. ### Method GET ### Endpoint /v1/car_data ### Query Parameters - **session_key** (string) - Required - Use 'latest' to get data from the current session. - **driver_number** (integer) - Required - The number of the driver to retrieve data for. ### Request Example ```bash curl "https://api.openf1.org/v1/car_data?session_key=latest&driver_number=1" ``` ``` -------------------------------- ### Get Session Schedule by Country, Session Name, and Year Source: https://context7.com/br-g/openf1/llms.txt Retrieve session schedule and metadata for a specific country, session name, and year. Updated daily at midnight UTC. ```bash # Belgium 2023 Sprint Qualifying session curl "https://api.openf1.org/v1/sessions?country_name=Belgium&session_name=Sprint%20Qualifying&year=2023" ``` ```javascript # All sessions in September 2023 fetch("https://api.openf1.org/v1/sessions?date_start>=2023-09-01&date_end<=2023-09-30") .then(r => r.json()) .then(sessions => sessions.forEach(s => console.log(s.session_name, s.country_name, s.date_start) )); ``` -------------------------------- ### Get Sessions by Date Range Source: https://context7.com/br-g/openf1/llms.txt Retrieve all sessions within a specified date range. ```APIDOC ## GET /v1/sessions ### Description Retrieves a list of F1 sessions based on specified date filters. ### Method GET ### Endpoint /v1/sessions ### Query Parameters - **date_start** (string) - Required - The start date for filtering sessions (YYYY-MM-DD). - **date_end** (string) - Required - The end date for filtering sessions (YYYY-MM-DD). ### Request Example ```bash curl "https://api.openf1.org/v1/sessions?date_start>=2023-09-01&date_end<=2023-09-30" ``` ``` -------------------------------- ### Get Sessions in September 2023 Source: https://context7.com/br-g/openf1/llms.txt Retrieve all sessions that occurred within September 2023. ```bash curl "https://api.openf1.org/v1/sessions?date_start>=2023-09-01&date_end<=2023-09-30" ``` -------------------------------- ### Fetch Session Results with Python Source: https://github.com/br-g/openf1/blob/main/documentation/includes/_api_endpoints.md Retrieve session results using Python's urllib.request. This example fetches results for a specific session key and filters by position. Pandas can be used to further process the data. ```python from urllib.request import urlopen import json response = urlopen('https://api.openf1.org/v1/session_result?session_key=7782&position%3C=3') data = json.loads(response.read().decode('utf-8')) print(data) # If you want, you can import the results in a DataFrame (you need to install the `pandas` package first) # import pandas as pd # df = pd.DataFrame(data) ``` -------------------------------- ### Set F1TV Token for Live Telemetry Source: https://github.com/br-g/openf1/blob/main/src/openf1/services/ingestor_livetiming/real_time/README.md To ingest live telemetry data, set the F1_TOKEN environment variable with a valid F1TV subscription token. Tokens typically expire every 4 days. ```bash export F1_TOKEN=... ``` -------------------------------- ### Fetch Lap Data using JavaScript Source: https://github.com/br-g/openf1/blob/main/documentation/includes/_api_endpoints.md Use the `fetch` API in JavaScript to retrieve and log lap data from the OpenF1 API. ```javascript fetch( "https://api.openf1.org/v1/laps?session_key=9161&driver_number=63&lap_number=8", ) .then((response) => response.json()) .then((jsonContent) => console.log(jsonContent)); ``` -------------------------------- ### GET /v1/session_result Source: https://context7.com/br-g/openf1/llms.txt Retrieves session results for a given session key, with optional filtering. ```APIDOC ## GET /v1/session_result — Session results Returns the final classification for a session. Available after the session has concluded. ### Parameters #### Query Parameters - **session_key** (integer) - Required - The unique identifier for the session. - **position** (integer) - Optional - Filter results by position (e.g., position<=3 for top 3). ### Request Example ```python import json from urllib.request import urlopen results = json.loads(urlopen( 'https://api.openf1.org/v1/session_result?session_key=7782&position%3C=3' ).read().decode('utf-8')) for r in results: print(f"P{r['position']}: Driver #{r['driver_number']} ({r['duration']}s)") ``` ### Response #### Success Response (200) - **position** (integer) - The driver's finishing position. - **driver_number** (integer) - The driver's unique number. - **duration** (string) - The driver's total race duration in seconds. - **meeting_key** (integer) - The unique identifier for the meeting. - **session_key** (integer) - The unique identifier for the session. ``` -------------------------------- ### Fetch Driver Profile Information with Python Source: https://context7.com/br-g/openf1/llms.txt Fetch driver profile data using Python. The response is a JSON array containing driver details, which can be accessed by index. ```python from urllib.request import urlopen import json driver = json.loads(urlopen('https://api.openf1.org/v1/drivers?driver_number=1&session_key=9158').read().decode())[0] print(f"{driver['full_name']} — #{driver['driver_number']} — {driver['team_name']}") # Max VERSTAPPEN — #1 — Red Bull Racing ``` -------------------------------- ### GET /v1/team_radio Source: https://context7.com/br-g/openf1/llms.txt Returns metadata and audio URLs for team radio communications captured during sessions. ```APIDOC ## GET /v1/team_radio — Driver-to-team radio clips Returns metadata and audio URLs for team radio communications captured during sessions. Only a selection of messages is included, not the full radio log. ### Parameters #### Query Parameters - **session_key** (integer) - Required - The unique identifier for the session. - **driver_number** (integer) - Optional - Filter clips by driver number. ### Request Example ```bash # Sergio Perez (11) radio clips during practice (session 9158) curl "https://api.openf1.org/v1/team_radio?session_key=9158&driver_number=11" ``` ### Response #### Success Response (200) - **date** (string) - The timestamp of the radio message. - **driver_number** (integer) - The driver's unique number. - **meeting_key** (integer) - The unique identifier for the meeting. - **recording_url** (string) - The URL to the audio recording of the radio message. - **session_key** (integer) - The unique identifier for the session. ``` -------------------------------- ### GET /v1/championship_teams Source: https://context7.com/br-g/openf1/llms.txt Retrieves team championship standings, including points and positions before and after a race session. ```APIDOC ## GET /v1/championship_teams ### Description Returns championship points and positions for constructors before and after a race session. ### Method GET ### Endpoint /v1/championship_teams ### Parameters #### Query Parameters - **session_key** (integer) - Required - The key of the session. - **team_name** (string) - Required - The name of the team. ### Request Example ```bash curl "https://api.openf1.org/v1/championship_teams?session_key=9839&team_name=McLaren" ``` ### Response #### Success Response (200) - **meeting_key** (integer) - The key of the meeting. - **points_current** (integer) - Points at the end of the session. - **points_start** (integer) - Points at the start of the session. - **position_current** (integer) - Position at the end of the session. - **position_start** (integer) - Position at the start of the session. - **session_key** (integer) - The key of the session. - **team_name** (string) - The name of the team. #### Response Example ```json [ { "meeting_key": 1276, "points_current": 833, "points_start": 800, "position_current": 1, "position_start": 1, "session_key": 9839, "team_name": "McLaren" } ] ``` ``` -------------------------------- ### Retrieve Driver Information (R) Source: https://github.com/br-g/openf1/blob/main/documentation/includes/_api_endpoints.md Fetches detailed information about a specific driver in a given session using R's httr and jsonlite libraries. Includes instructions for installing libraries and converting results to a DataFrame. ```r # If needed, install libraries # install.packages('httr') # install.packages('jsonlite') library(httr) library(jsonlite) response <- GET('https://api.openf1.org/v1/drivers?driver_number=1&session_key=9158') parsed_data <- fromJSON(content(response, 'text')) print(parsed_data) # If you want, you can import the results in a DataFrame # df <- do.call(rbind, lapply(parsed_data, data.frame, stringsAsFactors = FALSE)) # df <- as.data.frame(t(as.matrix(df))) ``` -------------------------------- ### Get Sessions Source: https://github.com/br-g/openf1/blob/main/documentation/includes/_api_endpoints.md Retrieves information about Formula 1 sessions. You can filter by country, session name, and year. ```APIDOC ## GET /sessions ### Description Provides information about sessions. A session refers to a distinct period of track activity during a Grand Prix or testing weekend (practice, qualifying, sprint, race, ...). Sessions are updated every day at midnight UTC. ### Method GET ### Endpoint https://api.openf1.org/v1/sessions ### Parameters #### Query Parameters - **country_name** (string) - Required - The name of the country where the session took place. - **session_name** (string) - Required - The name of the session (e.g., 'Sprint Qualifying', 'Race'). - **year** (integer) - Required - The year of the session. ### Response #### Success Response (200) - **circuit_key** (integer) - The unique identifier for the circuit. - **circuit_short_name** (string) - The short name of the circuit. - **country_code** (string) - The ISO 3166-1 alpha-3 country code. - **country_key** (integer) - The unique identifier for the country. - **country_name** (string) - The name of the country. - **date_end** (string) - The end date and time of the session in ISO 8601 format. - **date_start** (string) - The start date and time of the session in ISO 8601 format. - **gmt_offset** (string) - The GMT offset for the session's location. - **is_cancelled** (boolean) - Indicates if the session was cancelled. - **location** (string) - The location of the circuit. - **meeting_key** (integer) - The unique identifier for the meeting. - **session_key** (integer) - The unique identifier for the session. - **session_name** (string) - The name of the session. - **session_type** (string) - The type of the session. - **year** (integer) - The year of the session. ### Response Example ```json [ { "circuit_key": 7, "circuit_short_name": "Spa-Francorchamps", "country_code": "BEL", "country_key": 16, "country_name": "Belgium", "date_end": "2023-07-29T15:35:00+00:00", "date_start": "2023-07-29T15:05:00+00:00", "gmt_offset": "02:00:00", "is_cancelled": false, "location": "Spa-Francorchamps", "meeting_key": 1216, "session_key": 9140, "session_name": "Sprint Qualifying", "session_type": "Sprint Qualifying", "year": 2023 } ] ``` ``` -------------------------------- ### Obtain Access Token Source: https://github.com/br-g/openf1/blob/main/documentation/pages/auth.html This section provides examples for obtaining an access token using POST requests to the /token endpoint. The token is required for authenticating subsequent API calls. ```APIDOC ## Obtain Access Token ### Description Requests an access token by sending username and password to the token endpoint. ### Method POST ### Endpoint https://api.openf1.org/token ### Parameters #### Request Body - **username** (string) - Required - Your OpenF1 username. - **password** (string) - Required - Your OpenF1 password. ### Request Example (Python) ```python import requests token_url = "https://api.openf1.org/token" payload = { "username": "YOUR_USERNAME", "password": "YOUR_PASSWORD" } headers = { "Content-Type": "application/x-www-form-urlencoded" } response = requests.post(token_url, data=payload, headers=headers) if response.status_code == 200: token_data = response.json() print(f"Access token: {token_data.get('access_token')}") print(f"Expires in: {token_data.get('expires_in')} seconds") else: print(f"Error obtaining token: {response.status_code} - {response.text}") ``` ### Request Example (JavaScript) ```javascript async function getAccessToken() { const tokenUrl = "https://api.openf1.org/token"; const params = new URLSearchParams(); params.append("username", "YOUR_USERNAME"); params.append("password", "YOUR_PASSWORD"); try { const response = await fetch(tokenUrl, { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded", }, body: params, }); if (response.ok) { const tokenData = await response.json(); console.log("Access token:", tokenData.access_token); console.log("Expires in:", tokenData.expires_in, "seconds"); return tokenData.access_token; } else { console.error("Error obtaining token:", response.status, await response.text()); return null; } } catch (error) { console.error("Network error or other issue:", error); return null; } } ``` ### Response #### Success Response (200) - **expires_in** (string) - The time in seconds until the token expires. - **access_token** (string) - The obtained access token. - **token_type** (string) - The type of token, typically "bearer". ### Response Example ```json { "expires_in": "3600", "access_token": "YOUR_ACCESS_TOKEN", "token_type": "bearer" } ``` **Note:** Tokens expire after 1 hour. Applications should handle token expiry by requesting a new token. ``` -------------------------------- ### Get Session Results Source: https://github.com/br-g/openf1/blob/main/documentation/includes/_api_endpoints.md Retrieves standings after a specific session. This data is available shortly after official results are published. ```APIDOC ## GET /v1/session_result ### Description Provides standings after a session. This data becomes available a few minutes after the official results are published on the official Formula 1 website. ### Method GET ### Endpoint /v1/session_result ### Parameters #### Query Parameters - **session_key** (integer) - Required - The unique identifier for the session. - **position** (integer) - Optional - Filters results by position (e.g., `position<=3` for top 3). ### Request Example ``` https://api.openf1.org/v1/session_result?session_key=7782&position<=3 ``` ### Response #### Success Response (200) - **dnf** (boolean) - Indicates if the driver did not finish. - **dns** (boolean) - Indicates if the driver did not start. - **dsq** (boolean) - Indicates if the driver was disqualified. - **driver_number** (integer) - The driver's car number. - **duration** (float) - The duration of the session in seconds. - **gap_to_leader** (float) - The time gap to the leader. - **number_of_laps** (integer) - The total number of laps completed. - **meeting_key** (integer) - The unique identifier for the meeting. - **position** (integer) - The driver's finishing position. - **session_key** (integer) - The unique identifier for the session. #### Response Example ```json [ { "dnf": false, "dns": false, "dsq": false, "driver_number": 1, "duration": 77.565, "gap_to_leader": 0, "number_of_laps": 24, "meeting_key": 1143, "position": 1, "session_key": 7782 } ] ``` ``` -------------------------------- ### GET /v1/championship_drivers Source: https://context7.com/br-g/openf1/llms.txt Retrieves driver championship standings, including points and positions before and after a race session. This endpoint is in beta. ```APIDOC ## GET /v1/championship_drivers ### Description Returns championship points and positions for drivers before and after a race session. Only available for race sessions. ### Method GET ### Endpoint /v1/championship_drivers ### Parameters #### Query Parameters - **session_key** (integer) - Required - The key of the session. - **driver_number** (integer) - Required - The number of the driver. Can be specified multiple times for multiple drivers. ### Request Example ```bash curl "https://api.openf1.org/v1/championship_drivers?session_key=9839&driver_number=4&driver_number=81" ``` ### Response #### Success Response (200) - **driver_number** (integer) - The driver's number. - **meeting_key** (integer) - The key of the meeting. - **points_current** (integer) - Points at the end of the session. - **points_start** (integer) - Points at the start of the session. - **position_current** (integer) - Position at the end of the session. - **position_start** (integer) - Position at the start of the session. - **session_key** (integer) - The key of the session. #### Response Example ```json [ { "driver_number": 4, "meeting_key": 1276, "points_current": 423, "points_start": 408, "position_current": 1, "position_start": 1, "session_key": 9839 } ] ``` ``` -------------------------------- ### Check Code Style with Ruff Source: https://github.com/br-g/openf1/blob/main/CONTRIBUTING.md Run Ruff to check for linting issues. Use --format=github for GitHub Actions compatibility and --target-version=py310 for the Python version. ```bash ruff --format=github --ignore=E501 --target-version=py310 . ``` -------------------------------- ### Get Meetings Source: https://github.com/br-g/openf1/blob/main/documentation/includes/_api_endpoints.md Retrieves a list of meetings based on specified query parameters. Meetings are updated daily at midnight UTC. ```APIDOC ## GET /v1/meetings ### Description Provides information about meetings. A meeting refers to a Grand Prix or testing weekend and usually includes multiple sessions (practice, qualifying, race, ...). ### Endpoint https://api.openf1.org/v1/meetings ### Query Parameters - **year** (integer) - Required - The year of the meetings to retrieve. - **country_name** (string) - Optional - The name of the country to filter meetings by. ### Request Example ```shell curl "https://api.openf1.org/v1/meetings?year=2026&country_name=Singapore" ``` ### Response #### Success Response (200) - **circuit_key** (integer) - Unique identifier for the circuit. - **circuit_info_url** (string) - URL to detailed circuit information. - **circuit_image** (string) - URL to the circuit image. - **circuit_short_name** (string) - Short name of the circuit. - **circuit_type** (string) - Type of the circuit (e.g., 'Temporary - Street'). - **country_code** (string) - Two-letter country code. - **country_flag** (string) - URL to the country flag image. - **country_key** (integer) - Unique identifier for the country. - **country_name** (string) - Name of the country. - **date_end** (string) - The end date and time of the meeting (ISO 8601 format). - **date_start** (string) - The start date and time of the meeting (ISO 8601 format). - **gmt_offset** (string) - The GMT offset for the meeting location. - **is_cancelled** (boolean) - Indicates if the meeting is cancelled. - **location** (string) - The location of the circuit. - **meeting_key** (integer) - Unique identifier for the meeting. - **meeting_name** (string) - The name of the meeting. - **meeting_official_name** (string) - The official name of the meeting. - **year** (integer) - The year the meeting took place. ### Response Example ```json [ { "circuit_key": 61, "circuit_info_url": "https://api.multiviewer.app/api/v1/circuits/61/2026", "circuit_image": "https://media.formula1.com/content/dam/fom-website/2018-redesign-assets/Track%20icons%204x3/Singapore%20carbon.png", "circuit_short_name": "Singapore", "circuit_type": "Temporary - Street", "country_code": "SGP", "country_flag": "https://media.formula1.com/content/dam/fom-website/2018-redesign-assets/Flags%2016x9/singapore-flag.png", "country_key": 157, "country_name": "Singapore", "date_end": "2026-10-11T14:00:00+00:00", "date_start": "2026-10-09T09:30:00+00:00", "gmt_offset": "08:00:00", "is_cancelled": false, "location": "Marina Bay", "meeting_key": 1296, "meeting_name": "Singapore Grand Prix", "meeting_official_name": "FORMULA 1 SINGAPORE AIRLINES SINGAPORE GRAND PRIX 2026", "year": 2026 } ] ``` ``` -------------------------------- ### Download 2023 Sessions as CSV Source: https://context7.com/br-g/openf1/llms.txt Download all session data for the year 2023 in CSV format and save it to a file. ```bash curl "https://api.openf1.org/v1/sessions?year=2023&csv=true" -o sessions_2023.csv ``` -------------------------------- ### Retrieve Stint Data with JavaScript Source: https://github.com/br-g/openf1/blob/main/documentation/includes/_api_endpoints.md Use the `fetch` API in JavaScript to retrieve stint data from OpenF1. The response is parsed as JSON. ```javascript fetch("https://api.openf1.org/v1/stints?session_key=9165&tyre_age_at_start>=3") .then((response) => response.json()) .then((jsonContent) => console.log(jsonContent)); ``` -------------------------------- ### Fetch Meetings Data (Shell) Source: https://github.com/br-g/openf1/blob/main/documentation/includes/_api_endpoints.md Use curl to make a GET request to the meetings endpoint, filtering by year and country. ```shell curl "https://api.openf1.org/v1/meetings?year=2026&country_name=Singapore" ``` -------------------------------- ### Configure MongoDB Connection String Source: https://github.com/br-g/openf1/blob/main/README.md Set the MONGO_CONNECTION_STRING environment variable to connect to your local MongoDB instance. This is required for running the project locally. ```bash export MONGO_CONNECTION_STRING="mongodb://localhost:27017" ``` -------------------------------- ### Get Latest Car Data for Driver 1 Source: https://context7.com/br-g/openf1/llms.txt Fetch car data for driver number 1 from the most recent session. ```bash curl "https://api.openf1.org/v1/car_data?session_key=latest&driver_number=1" ```