import matlab.net.* import matlab.net.http.* import matlab.net.http.field.* import matlab.net.http.io.* %% Obtain API Access Token % Add your Client-ID and Client-secret from the API Client configuration GUI to % your environment variable first IPNT_CLIENT_ID = getenv('IPNT_CLIENT_ID'); IPNT_CLIENT_SECRET = getenv('IPNT_CLIENT_SECRET'); % URL to request token from scope = URI('https://identity.netztransparenz.de/users/connect/token'); % 20 second timeout opts = HTTPOptions('ConnectTimeout', 20); % Send request (url encoded form data) body = FormProvider('grant_type', 'client_credentials', ... 'client_id', IPNT_CLIENT_ID, ... 'client_secret', IPNT_CLIENT_SECRET); request = RequestMessage('POST',[],body); resp = request.send(scope, opts); % Status code is OK if request was processed correctly if resp.StatusCode ~= StatusCode.OK error('Failed to obtain an access token for IPNT'); end %% Download data as .csv from = datetime('yesterday')-days(7); to = datetime('yesterday'); data = 'hochrechnung'; product = 'solar'; % Read the access token from the response body token = resp.Body.Data.access_token; % This is the base URL for querying data baseURL = 'https://ds.netztransparenz.de/api/v1/data'; % Create message header that include access token header = [ContentTypeField('application/x-www-form-urlencoded'), ... AcceptField('text/plain'), ... HeaderField('Authorization', ['Bearer ', token])]; % TimeZone needs to be UTC for our requests from.TimeZone = 'UTC'; to.TimeZone = 'UTC'; % Build URL to data scope = strjoin({baseURL, data, product, ... datestr(from, 'yyyy-mm-ddTHH:MM:SS'), ... datestr(to, 'yyyy-mm-ddTHH:MM:SS')} , '/'); % We download to a .csv-File from.TimeZone = 'Europe/Zurich'; to.TimeZone = 'Europe/Zurich'; filename = [strjoin({datestr(from, 'yyyymmdd'), ... datestr(to, 'yyyymmdd'), ... data, product } , '_') '.csv']; % Do nothing if the file already exists (no overwriting) if ~exist(filename, 'file') % Open the file for writing sinkFID = fopen(filename, 'w'); % Send download request request = RequestMessage('GET', header); % FileConsumer is used to write message payload directly to a file resp = request.send(scope, opts, FileConsumer(sinkFID)); % Close the file again fclose(sinkFID); end