Introduction (Read REST / SOAP API in SSRS)
In this tutorial, you will learn how to read REST API in SSRS (SQL Server Reporting Services). Traditionally to read data from XML / JSON Files or RESTful web service in SSRS, some sort of ETL approach was needed (i.e Load data from JSON / XML to SQL server first and then read from SQL Server to SSRS).
This article will focus on very unique and simple approach, we will use ZappySys drivers for JSON / XML / REST API to read REST API or JSON Files in SSRS reports. ZappySys JSON driver allows you to query any API source or JSON / XML files using familiar SQL query language.
Example purpose, we will only show JSON file format but the same approach can be used for reading from XML files or Calling XML SOAP Web Services in SSRS. We will also learn how to connect using OAuth to Facebook. We can also connect to Google, Azure, Facebook, Twitter, DropBox, Github, Instagram and thousands of other sources using same techniques.
Finally, we will also learn how to handle errors, pagination to handle several pages and how to read an XML file in Reporting Services
Requirements:
- Make sure you have SSRS designer installed (You can download SSDT BI for Visual Studio 2015).
- In addition, we will need ZappySys ODBC PowerPack Installed.
Getting Started
You can access JSON / XML data in SSRS three different ways. We will only focus on one method in this article but please check other articles by clicking below links.
- ZappySys Data Gateway – This method uses Microsoft SQL Server Connection Type option to connect to ZappySys Data Gateway. Check this
- Microsoft SQL Server (Linked Server) – This connection type which connects to SQL Server Linked Server. Check this
- ODBC (Use ZappySys ODBC Driver) – You can use ODBC connection option in Report when you define data source (NOTE: There are some known issues with this method so we will not discuss)
Now lets look at steps to call REST API in SSRS (SQL Server reporting Services).
Configure Data Source in Gateway (ZappySys JSON / REST API Driver Example)
Configure Data Gateway User / Port
Now let's look at steps to configure Data Gateway after installation. We will also create a sample data source for ODATA API (i.e. JSON based REST API Service).- Assuming you have installed ZappySys ODBC PowerPack using default options (Which also enables Data Gateway Service)
- Search "Gateway" in your start menu and click ZappySys Data Gateway
- First make sure Gateway Service is running (Verify Start icon is disabled)
- Also verify Port on General Tab
- Now go to Users tab. Click Add icon to add a new user. Check Is admin to give access to all data sources you add in future. If you don't check admin then you have to manually configure user permission for each data source.
Configure Data Source
- After user is added, go to Data Sources tab. Click Add icon to create new data source. Select appropriate driver based on your API / File format. You can choose Generic ODBC option to read data from ODBC DSN or use Native Driver option.
NOTE: Whenever possible use native driver option for better performance / security and ease of use.
- Click on "Edit" under Data source and configure as per your need (e.g. Url, Connection, Request Method, Content Type, Body, Pagination etc.). For this demo we are going to pick simple JSON REST API which doesn't need any authentication. Enter following URL.
https://services.odata.org/V3/Northwind/Northwind.svc/Invoices?$format=json
- You can also view response structure and select default hierarchy (i.e. Filter) like below (Select Array Icon) for data extraction.
Test SQL Query / Preview Data
- Now go to Preview Tab. You can click Preview button to execute default query OR Select Table name from dropdown to generate SQL with column names.
- You can also click Query Builder to generate SQL using different options in WITH clause. ANy setting you specify in WITH clause will override UI settings we applied in previous steps.
- There is another useful option for code generation. Select your Language and quickly copy code snippet. See below Example of XML Driver Query to call SOAP API.
- Click OK to Close Data Source UI
- Once data source is tested and configured you can click Save button in the Gateway UI toolbar and click Yes for Restart Service.
Configure SSRS Report Data source (Use ODBC Connection)
Once you are done configuring ODBC DSN for REST API URL. The next step will be to create a new SSRS project.
- In SSRS, in a new Reporting Service Project, add a new Data Source:
- Also, specify a name for the data source and in type select Microsoft SQL Server. Press Build to select the Data gateway connection information as below.
- Click OK to save our data source. We will use this Data source in next section.
Create a new SSRS Report
Once your DSN is setup we can create report. There are two ways you can create reports.
- Create SSRS Reports using Report Builder App
- Create SSRS Reports using Visual Studio (SSDT) – Download SSDT from Here
In this section we will see second method (Visual Studio Method). Now let’s create a new SSRS report which uses the API data source we created in the previous section.
- Open Existing SSRS Project or Create a new Reporting Services Project by clicking File > New. When Dialog Opens expand Business Intelligence category and select Reporting Services Project
- When Solution opens Right-click on the Reports node and click Add New Report (Wizard mode)
- Press the query builder button
- Additionally, press the Add table icon and go to Views. Select value(DATA) and press add:
- Press next in the following option until the completing wizard and specify a name for the report and check the option to Preview a report:
- If everything is OK, you will be able to see the report and export the REST API data to Word, Excel, PowerPoint, etc:
Export JSON and REST API to word, Excel
Working with parameters in SSRS (Dynamic SQL Query)
So far we have seen how to pull data from Table exposed by our ODBC DSN for API Service. In the real world, you may have some sort of parameters passed to your API Service (e.g. CustomerID or Date Parameters).
So let’s configure our report to use parameters.
- We can work with parameters in SSRS. You can Add a Parameter in Parameters with the add parameter option:
- We will create a parameter named CustomerID and it will be used to assign a customerID parameter:
- Create a data source and a dataset, drag and drop your columns to the report:
- Right-click your DataSet (which was generated by Report Wizard) and select DataSet properties:
- Go to query and select Fx to create a dynamic SQL Query for our data source (Use expression / parameters in SQL):Just keep in mind that, if you use dynamic SQL for the data source (i.e. Using Expression in SQL) then Fields of that data source won’t refresh automatically when you save the UI. Workaround for this issue simple. Just use a static query for the first time to generate desired fields for the dataset. Once data source fields are generated you can add expression in your SQL Query.
Static Query:
SELECT col1, col2 FROM rows WITH (SRC=’http://abc.com/invoice?year=2017′)
Dynamic Query:
=”select col1, col2 from rows WITH (SRC=’http://abc.com/invoice?year='” + Parameters!Year.Value + “‘)” - On the expression dialog box, Enter SQL Query like below
12="SELECT CustomerID, CompanyName, ContactName FROM value where CustomerID='"+ Parameters!CustomerID.Value + "'" - If you don’t want to use URL from DSN then you can supply API URL right inside your SQL Query like below.
123="SELECT CustomerID, CompanyName, ContactName FROM value where CustomerID='"+ Parameters!CustomerID.Value + "'" +"WITH (SRC='https://services.odata.org/V3/Northwind/Northwind.svc/Invoices?$format=json')" - You can now write a name as a parameter and receive the results:
Working with multi-value parameters in SSRS (Dynamic SQL Query)
If you have a parameter which is multi-valued and you want to use it to filter data then follow the above section and in the expression dialog box use JOIN function to join the values, e.g.:
=SELECT CustomerID, CompanyName, ContactName FROM value where CustomerID IN ('" & JOIN(Parameters!CustomerID.Value, "','") & "')"
Working with SSRS dataset filters (Client-side filtering)
Sometimes its necessary to do filtering on data once it’s retrieved from the server. Dataset Filter is SSRS feature which does data filtering on the client side. To filter the report previously created, right click on the dataset and go to Filters. Press Add.
In this example, we will show how to show a customer with the customerID equal to ALFKI (or click on fx icon to use the expression for dynamic filter:
Add filter SSRS REST API
Working with date parameters in SSRS Reports
Now lets look at how to handle date parameters and format them correctly. Most JSON /XML REST API handle dates in ISO format (i.e. yyyy-MM-ddTHH:mm:ss.fffZ). You can convert or format text parameters to date using the CDate function. The following example converts the parameter mydate from text to a date in SSRS:
1 |
CDate( Parameters!mydate.Value) |
Next, we will show how to convert the date format to the format yyyy-MM-ddT00:00:00:
1 |
FORMAT(CDate( Parameters!mydate.Value),"yyyy-MM-ddT00:00:00") |
Also, we will work with a REST API URL with data and retrieve the results:
1 |
https://services.odata.org/V3/Northwind/Northwind.svc/Invoices?$format=json |
Furthermore, in the ODBC Administrator add a connection to the previous URL (Or use URL inside SQL query WITH caluse as per previous section example):
The following example will convert the parameter to the same format as the URL and compare the OrderDate to the specified format:
1 2 |
="SELECT ShipName, ShipAddress, OrderDate FROM DATA.""value"" where OrderDate="+"'"+Cstr(FORMAT(CDate( Parameters!mydate.Value),"yyyy-MM-ddT00:00:00"))+"'" |
Pass parameters in a Report URL
In addition, when the report is published, you can specify a parameter in a URL. The following example shows how to pass a date in a parameter named mydate the value 1997-10-13:
1 2 |
http://localhost/ReportServer/Pages/ReportViewer.aspx?%2fReport+Project5 %2fReport5&rs:Command=Render&mydate=1997-10-13 |
Read JSON files in SSRS Reports
Also, it is possible to connect to a JSON file instead of REST API. The steps are the same that the ones explained previously with the difference that we need to specify the path when we create the ODBC connection. The following example with show how to specify the path of a local JSON file in the connection:
Reading XML Files in SSRS Reports
The next example will show how to read an XML file using SSRS.
The XML name is ZS.xml and it contains the following content:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 |
<?xml version="1.0"?> <store storeid="s1"> <book id="bk101"> <author>Gambardella, Matthew</author> <title>XML Developer's Guide</title> <genre>Computer</genre> <price>44.95</price> <publish_date>2000-10-01</publish_date> <description>An in-depth look at creating applications with XML.</description> </book> <book id="bk102"> <author>Ralls, Kim</author> <title>Midnight Rain</title> <genre>Fantasy</genre> <price>5.95</price> <publish_date>2000-12-16</publish_date> <description>A former architect battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world.</description> </book> <book id="bk103"> <author>Corets, Eva</author> <title>Maeve Ascendant</title> <genre>Fantasy</genre> <price>5.95</price> <publish_date>2000-11-17</publish_date> <description>After the collapse of a nanotechnology society in England, the young survivors lay the foundation for a new society.</description> </book> <book id="bk104"> <author>Corets, Eva</author> <title>Oberon's Legacy</title> <genre>Fantasy</genre> <price>5.95</price> <publish_date>2001-03-10</publish_date> <description>In post-apocalypse England, the mysterious agent known only as Oberon helps to create a new life for the inhabitants of London. Sequel to Maeve Ascendant.</description> </book> <book id="bk105"> <author>Corets, Eva</author> <title>The Sundered Grail</title> <genre>Fantasy</genre> <price>5.95</price> <publish_date>2001-09-10</publish_date> <description>The two daughters of Maeve, half-sisters, battle one another for control of England. Sequel to Oberon's Legacy.</description> </book> <book id="bk106"> <author>Randall, Cynthia</author> <title>Lover Birds</title> <genre>Romance</genre> <price>4.95</price> <publish_date>2000-09-02</publish_date> <description>When Carla meets Paul at an ornithology conference, tempers fly as feathers get ruffled.</description> </book> <book id="bk107"> <author>Thurman, Paula</author> <title>Splish Splash</title> <genre>Romance</genre> <price>4.95</price> <publish_date>2000-11-02</publish_date> <description>A deep sea diver finds true love twenty thousand leagues beneath the sea.</description> </book> <book id="bk108"> <author>Knorr, Stefan</author> <title>Creepy Crawlies</title> <genre>Horror</genre> <price>4.95</price> <publish_date>2000-12-06</publish_date> <description>An anthology of horror stories about roaches, centipedes, scorpions and other insects.</description> </book> <book id="bk109"> <author>Kress, Peter</author> <title>Paradox Lost</title> <genre>Science Fiction</genre> <price>6.95</price> <publish_date>2000-11-02</publish_date> <description>After an inadvertant trip through a Heisenberg Uncertainty Device, James Salway discovers the problems of being quantum.</description> </book> <book id="bk110"> <author>O'Brien, Tim</author> <title>Microsoft .NET: The Programming Bible</title> <genre>Computer</genre> <price>36.95</price> <publish_date>2000-12-09</publish_date> <description>Microsoft's .NET initiative is explored in detail in this deep programmer's reference.</description> </book> <book id="bk111"> <author>O'Brien, Tim</author> <title>MSXML3: A Comprehensive Guide</title> <genre>Computer</genre> <price>36.95</price> <publish_date>2000-12-01</publish_date> <description>The Microsoft MSXML3 parser is covered in detail, with attention to XML DOM interfaces, XSLT processing, SAX and more.</description> </book> <book id="bk112"> <author>Galos, Mike</author> <title>Visual Studio 7: A Comprehensive Guide</title> <genre>Computer</genre> <tag>tag1</tag> <price>49.95</price> <publish_date>2001-04-16</publish_date> <description>Microsoft Visual Studio 7 is explored in depth, looking at how Visual Basic, Visual C++, C#, and ASP+ are integrated into a comprehensive development environment.</description> </book> </store> |
This example will read an XML file named ZS.xml. First, in ODBC Administrator add the ZappySys ODBC XML Driver:
In data source, specify the path of the file:
Once created the connection, create your report in SSDT in the query, add the following query:
SELECT author, genre, title, price, publish_date
FROM DATA.”store.book”
Finally, you can visualize your report in SSRS:
REST API Security – Working with OAuth (Facebook API example)
If you API requires credentials then no worries, ZappySys Drivers come with many security standards support. Most common credential types are Basic Auth and OAuth. These are open standard to access Web Services. In this new example, we will show how to read Facebook information in SSRS (Call Facebook Graph API).
For demo we will read the number of friends on Facebook:
First, we will open the ODBC Data Source:
In Authentication type, select OAuth. We will use the following link to get the friends information on Facebook:
1 |
https://graph.facebook.com/v1.0/me/friends? |
This link retrieves information of my friends. For more information about the Facebook graph API, check our references.
Secondly, go to OAuth settings and select Facebook as the OAuth Provider. You will need a Client Id and a Client Secret. To get a client id and a client secret, you will need to create a Facebook application here. For more information about creating a Facebook application, check this link.
Scopes will use user_friends to get Facebook friends information. For a list of scopes, please check here.
Once that the connection is created, you need to create an SSRS report using the ODBC connection just created. In the query, we will create the following query:
If everything is OK, you will be able to see the number of Facebook friends:
POST Parameters to SSRS Report (avoid GET for long string in URL)
You can call reports from browser using following way (Pass parameters in URL). Below Method by default sends GET requests to Report Server and render report in HTML format in your browser.
1 |
http://localhost/reports/report/MySampleReports/Report1?MyParameter1=AAA&MyParameter2=BBB |
However there is a problem if you have a very long string as parameter value. In that case use FORM POST method described in this article.
You can try yourself. Just create an html file on your machine and paste below code. Run it in a browser (If you have UAC ON then First launch Browser as Admin and then paste full path of your HTML file). Click on a button displayed in that page to mimic POST.
TestPost.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<html> <body> <!-- use _self or _blank to control where report opens... same window or new window ? --> <form id="frmRender" action="http://localhost/ReportServer/Pages/ReportViewer.aspx?/MyProject1/Report1" method="post" target="_blank"> <!-- <form id="frmRender" action="http://localhost/reportserver?/MyProject1/Report1" method="post" target="_self"> --> <input type="hidden" name="rs:Command" value="Render" /> <input type="hidden" name="rc:LinkTarget" value="_blank" /> <input type="hidden" name="rs:Format" value="HTML4.0" /> <!-- report format --> <input type="hidden" name="rc:Parameters" value="false" /> <!-- display report parameters --> <input type="submit" value="Open Report With Parameters (POST Example)"> <br /> <br /> Fill out below parameters and click above button <br /> <br /> <input name="Notes" name="Notes" value="xyz-long-string-goes-here" /> <!-- <input type="hidden" name="param2" value="xxxx" /> --> </form> </body> </html> |
You can use expression like below in your Report to confirm Data Length of posted Parameter
1 |
="My Parameter Length is " & Parameters!Notes.Value.ToString().Length |
Also you can use below expression to make your query dynamic as below
1 2 3 4 5 6 |
="SELECT data,origin,url FROM _root_ " + "WITH(SRC='http://httpbin.org/post', " + "METHOD='POST', " + "HEADER='Content-Type: text/plain', " + "BODY='" + Parameters!Notes.Value + "')" |
Deploying SSRS Report (for ODBC Connection)
NOTE: In this section we will make sure few thing for ODBC Connection Type. If you used Data Gateway approach then you may skip this section.
Once you done with design and testing of reports, our next step would be deploy reports to SSRS Server. This section describes things to make sure when you deploy reports.
Find DSN Name and Full ConnectionString of original DSN
- First thing to make sure you install ODBC PowerPack on the report server too (Unless you are using SQL Server Connection Type to connect to Gateway and you dont plan to run it on SSRS Server)
- Once ODBC PowerPack is installed on the server next step is to setup DSN Used by Reports. SSRS Service is 64 bit so DSN must be 64 bit and must be named Exact same way just like how you used during Design Phase on Client PC where reports are designed.
- To Setup DSN exact same way try this step. First go to Client PC where reports are designed. Open ODBC DSN which you used for Report. Copy two things 1) Name of your DSN, and Find Copy Connection String Button to copy full connection string of your DSN.
Create new DSN(s) on SSRS Server using original settings
- Now Remote Desktop (rdp) to SSRS Server, search of odbc 64 bit. Open it and go to System Tab.
- Click Add to create new DSN just like we did very beginning of this article. Select Driver you wish to use.
- Once Driver UI opens up change default DSN name to exact same name like we gave it for SSRS Report on client PC.
- find Load Connection String Button and paste connection string we obtained in previous step.
- Click Test connection see everything good. Click OK to save DSN
- Repeat these steps for each DSN used in SSRS Report.
Things to know about SSRS 2017 or Higher / Report Builder
We had few users who reported issue with SSRS 2017 after deployment (Everything worked fine during design time). You may get below error when try to preview report from server URL. You may sometimes notice that after saving report in Report Builder if you try to preview Report Builder hangs and you have to restart SSRS service. If you notice any such issue you may have to apply following fix..
Error:
1 |
Cannot create a connection to data source 'YourDataSourceName'. ---> System.Data.Odbc.OdbcException: |
In such case check steps listed in Troubleshooting Section later this article.
Calling SOAP XML Web Service in SSRS (SQL Reporting Services)
So far we have looked at examples to consume data using JSON driver. Now let’s look at an example, to call XML SOAP Web Service in SSRS.
What is SOAP Web Service?
If you are new to SOAP Web Service sometimes referred as XML Web Service then please read some concept about SOAP Web service standard from this link There are two important aspects in SOAP Web service.- Getting WSDL file or URL
- Knowing exact Web Service URL
What is WSDL
In very simple term WSDL (often pronounced as whiz-dull) is nothing but a document which describes Service metadata (e.g. Functions you can call, Request parameters, response structure etc). Some service simply give you WSDL as xml file you can download on local machine and then analyze or sometimes you may get direct URL (e.g. http://api.mycompany.com/hr-soap-service/?wsdl )Example SQL Query for SOAP API call using ZappySys XML Driver
Here is an example SQL query you can write to call SOAP API. If you not sure about many details then check next few sections on how to use XML Driver User Interface to build desired SQL query to POST data to XML SOAP Web Service without any coding.SELECT * FROM $ WITH( Src='http://www.holidaywebservice.com/HolidayService_v2/HolidayService2.asmx' ,DataConnectionType='HTTP' ,CredentialType='Basic' --OR SoapWss ,SoapWssPasswordType='PasswordText' ,UserName='myuser' ,Password='pass$$w123' ,Filter='$.soap:Envelope.soap:Body.GetHolidaysAvailableResponse.GetHolidaysAvailableResult.HolidayCode[*]' ,ElementsToTreatAsArray='HolidayCode' ,RequestMethod='POST' ,Header='Content-Type: text/xml;charset=UTF-8 || SOAPAction: "http://www.holidaywebservice.com/HolidayService_v2/GetHolidaysAvailable"' ,RequestData=' <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:hol="http://www.holidaywebservice.com/HolidayService_v2/"> <soapenv:Header/> <soapenv:Body> <hol:GetHolidaysAvailable> <!--type: Country - enumeration: [Canada,GreatBritain,IrelandNorthern,IrelandRepublicOf,Scotland,UnitedStates]--> <hol:countryCode>UnitedStates</hol:countryCode> </hol:GetHolidaysAvailable> </soapenv:Body> </soapenv:Envelope>' )Now let's look at steps to create SQL query to call SOAP API. Later we will see how to generate code for your desired programming language (e.g. C# or SQL Server)
Video Tutorial - Introduction to SOAP Web Service and SoapUI tool
Before we dive into details about calling SOAP API using ZappySys XML Driver, lets first understand what is SOAP API and how to create SOAP requests using SoapUI tool. You will learn more about this process in the later section. The video contains some fragment about using SOAP API in SSIS but just ignore that part because we will be calling Soap API using ZappySys ODBC Driver rather than SSIS Components.Using SoapUI to test SOAP API call / Create Request Body XML
Assuming you have downloaded and installed SoapUI from here, now we are ready to use WSDL for your SOAP Web Service Calls. If you do not have WSDL file or URL handy then contact your API provider (sometimes you just have to add ?wsdl at the end of your Service URL to get WSDL so try that. Example: http://mycompany/myservice?wsdl ). If you don't know what is WSDL then in short, WSDL is Web service Description Language (i.e. XML file which describes your SOAP Service). WSDL helps to craft SOAP API request Body for ZappySys XML Driver. So Let's get started.- Open SoapUI and click SOAP button to create new SOAP Project
- Enter WSDL URL or File Path of WSDLFor example WSDL for our sample service can be accessed via this URL
http://www.dneonline.com/calculator.asmx?wsdl
Create new SOAP API Project in SoapUI tool for SOAP API Testing - Once WSDL is loaded you will see possible operations you can call for your SOAP Web Service.
- If your web service requires credentials then you have to configure it. There are two common credential types for public services (SOAP WSS or BASIC )
-
To use SOAP WSS Credentials select request node and enter UserId, Password, and WSS-PasswordType (PasswordText or PasswordHash)Configure SOAP WSS Credentials for SoapUI (SOAP API Testing Tool)
- To use BASIC Auth Credentials select request node and double-click it. At the bottom click on Auth (Basic) and From Authorization dropdown click Add New and Select Basic.
Configure Basic Authorization for SoapUI (SOAP API Testing Tool)
-
- Now you can test your request first Double-click on the request node to open request editor.
- Change necessary parameters, remove optional or unwanted parameters. If you want to regenerate request you can click on Recreate default request toolbar icon.
Create SOAP Request XML (With Optional Parameters)
- Once your SOAP Request XML is ready, Click the Play button in the toolbar to execute SOAP API Request and Response will appear in Right side panel. Test SOAP API using SoapUI Tool (Change Default XML Body / Parameters, Execute and See Response)
Create DSN using ZappySys XML Driver to call SOAP API
Once you have tested your SOAP API in SoapUI tool, we are ready to use ZappySys XML driver to call SOAP API in your preferred BI tool or Programming language.- First open ODBC Data Sources (search ODBC in your start menu or go under ZappySys > ODBC PowerPack > ODBC 64 bit)
- Goto System DSN Tab (or User DSN which is not used by Service account)
- Click Add and Select ZappySys XML Driver ZappySys ODBC Driver for XML / SOAP API
- Configure API URL, Request Method and Request Body as below ZappySys XML Driver - Calling SOAP API - Configure URL, Method, Body
- (This step is Optional) If your SOAP API requires credentials then Select Connection Type to HTTP and configure as below.
ZappySys XML Driver - Configure SOAP WSS Credentials or Basic Authorization (Userid, Password)
- Configure-Request Headers as below (You can get it from Request > Raw tab from SoapUI after you test the request by clicking the Play button) Configure SOAP API Request Headers - ZappySys XML Driver
- Once credentials entered you can select Filter to extract data from the desired node. Make sure to select array node (see special icon) or select the node which contains all necessary columns if you don't have array node. Select Filter - Extract data from nested XML / SOAP API Response (Denormalize Hierarchy)
- If prompted select yes to treat selected node as Array (This is helpful when you expect one or more record for selected node) Treat selected node as XML Array Option for SOAP API Response XML
Preview SOAP API Response / Generate SQL Code for SOAP API Call
Once you configure settings for XML Driver now you can preview data or generate example code for desired language (e.g. C#, Python, Java, SQL Server). Go to Preview tab and you will see default query generated based on settings you entered in previous sections. Attributes listed in WITH clause are optional. If you omit attribute in WITH clause it will use it from Properties tab.Preview Data
Preview SOAP API Response in ZappySys XML DriverGenerate Code Option
SOAP / REST API pagination in SSRS Reports
Paginate by Response Attribute
This example shows how to paginate API calls where you need to paginate until the last page detected. In this example, next page is indicated by some attribute called nextlink (found in response). If this attribute is missing or null then it stops fetching the next page.SELECT * FROM $ WITH( SRC=@'https://zappysys.com/downloads/files/test/pagination_nextlink_inarray_1.json' ,NextUrlAttributeOrExpr = '$.nextlink' --keep reading until this attribute is missing. If attribute name contains dot then use brackets like this $.['my.attr.name'] )
Paginate by URL Parameter (Loop until certain StatusCode)
This example shows how to paginate API calls where you need to pass page number via URL. The driver keeps incrementing page number and calls next URL until the last page detected (401 error). There are few ways to indicate the last page (e.g. By status code, By row count, By response size). If you don't specify end detection then it will use the default (i.e. No records found).SELECT * FROM $ WITH ( SRC=@'https://zappysys.com/downloads/files/test/page-xml.aspx?page=1&mode=DetectBasedOnResponseStatusCode' ,PagingMode='ByUrlParameter' ,PagingByUrlAttributeName='page' ,PagingByUrlEndStrategy='DetectBasedOnResponseStatusCode' ,PagingByUrlCheckResponseStatusCode=401 ,IncrementBy=1 )
Paginate by URL Path (Loop until no record)
This example shows how to paginate API calls where you need to pass page number via URL Path. The driver keeps incrementing page number and calls next URL until the last page is detected. There are few ways to indicate the last page (e.g. By status code, By row count, By response size). If you don't specify end detection then it will use the default (i.e. No records found).SELECT * FROM $ WITH ( SRC=@'https://zappysys.com/downloads/files/test/cust-<%page%>.xml' ,PagingMode='ByUrlPath' ,PagingByUrlAttributeName='<%page%>' ,PagingByUrlEndStrategy='DetectBasedOnRecordCount' ,IncrementBy=1 )
Paginate by Header Link (RFC 5988)
API like GitHub / Wordpress use Next link in Headers (RFC 5988)SELECT * FROM $ LIMIT 25 WITH( Src='https://wordpress.org/news/wp-json/wp/v2/categories?per_page=10' ,PagingMode='ByResponseHeaderRfc5988' ,WaitTimeMs='200' --//wait 200 ms after each request )
SOAP / REST API Error Handling in SSRS Reports
METHOD 1 - Using Error Handling Options
When to use?
You may want to use them when your source is a resource located on the Internet; e.g. a file on a website, a file on an FTP server or just a plain API HTTP response. By default, when a remote server returns an error, data retrieval is stopped, an error is raised and no data is given back to you. This might not be always desirable.Scenario 1
Imagine a scenario, that there is a web server which each day at 12 AM releases a new JSON file with that day's date as filename, e.g. http://www.some-server.com/data/2018-06-20.json. And, of course, you want to download it and use it daily in your Power BI report. But you have a problem: Power BI report data sources are refreshed each hour and you may get HTTP 404 status code (no file was found) when a file is not released yet. Which consequentially means other data sources won't be updated as well and you will see old and cached data on the report. That's where you could use Continue on any error or Continue when Url is invalid or missing (404 Errors) to avoid an error being raised and let other data sources to be updated.Scenario 2
Another scenario is when you expect a web server to raise some kind of HTTP error when accessing a URL. You don't want ODBC Data Source to raise an error but instead, you want to get response data. That's where you can use Continue on any error or alike together with Get response data on error to continue on an error and get the data:METHOD 2 - Using Connection [Retry Settings]
Another scenario you may run into is a buggy web server. You ask it to give you some file or data and it, like a snotty kid, just doesn't give it to you! You have to ask twice or thrice before it does its job. If that's the case, you have to retry HTTP requests using Connection:Security / Connection Types (Options for HTTP, OAuth, SOAP) in SSRS Reports
- HTTP
- OAuth
HTTP Connection
- SOAP WSS (when accessing a SOAP WebService)
- Static Token / API Key (when need to pass an API key in HTTP header)
- Dynamic Token (same as Static Token method except that each time you need to log in and retrieve a fresh API key)
- JWT Token (As per RFC 7519)
OAuth
If you are trying to access REST API resource, it is a huge chance, you will need to use OAuth Connection. Read this article to understand how OAuth authentication and authorization works and how to use it (article originally was written for SSIS PowerPack, but the concepts and UI stay the same): https://zappysys.com/blog/rest-api-authentication-with-oauth-2-0-using-ssisOther Consideration for Calling Web API in SSRS Reports
API Limit / Throttling
While calling public API or other external web services one important aspect you have to check, how many requests are allowed by your API. Especially when you use API pagination options to pull many records you have to slow down based on API limits. For example, your API may allow you only 5 requests per second. Use Throttling Tab on Driver UI to set delay after each request.2D Array Transformation
If you are using JSON or XML API Driver then possible you may have to transform your data using 2D array transformation feature. Check this link for more information.Working with pagination to read REST API using SSRS
Another important aspect of any API call is handling pagination. When you have many records to read from API, most likely your API won’t send you data in one response. You have to loop through all pages of data until the last page is detected. ZappySys driver comes with many options to configure virtually any pagination strategy.
Here is the screenshot of Pagination options included in ZappySys JSON / XML API Driver:
Moreover, you can configure the maximum page number and the response length. It is also possible to set the minimum response length.
In addition, you can also configure the page number increment and pagination mode. You can also specify conditions to detect the last page and more.
Reading API data from SQL Server Stored Procedure
If you want to read data from SQL Server Stored procedure rather than using Data gateway or ODBC connection then check this post.
Handling errors to read REST API using SSRS
The ZappySys ODBC PowerPack allows handling errors. For example, if the page is not found (error 404), the driver can continue working. You can also continue on any error. Continue on status code, stop the execution on error or more options:
Troubleshooting SSRS Issues
If you experience problems accessing data from ODBC data source, you may try to set up a data source in ZappySys Data Gateway and access it instead. Check how to troubleshoot errors when SSRS crashes to find out how to accomplish that.
Report Builder Hangs / ODBC Connection errors in SSRS 2017 or Higher
Sometimes you may notice that after saving Report to Server in Report Builder when you preview it hangs or you may get below error. This issue may occur If you are using SSRS 2017 or higher and report is using ODBC Connection Type. If your preview hangs or get below error then you have to try few steps listed below to avoid such error. This error may occur in other version too but from our experience it mostly happens in newer SSRS version.
1 |
ERROR : Cannot create a connection to data source 'YourDataSourceName'. ---> System.Data.Odbc.OdbcException: |
Steps to fix this error.
- First we have to Gac Newtonsoft.json.dll. For this search for “Powershell ISE” and right click and launch as Admin
- Run below command to register Dll
1234[Reflection.Assembly]::LoadWithPartialName("System.EnterpriseServices") | Out-Null[System.EnterpriseServices.Internal.Publish] $publish = new-object System.EnterpriseServices.Internal.Publish$publish.GacInstall("C:\Program Files (x86)\ZappySys\ZappySys ODBC PowerPack\JsonDriverX86\Newtonsoft.Json.dll") - Now go to SSRS Install folder typically found here
1C:\Program Files\Microsoft SQL Server Reporting Services\SSRS\ReportServer - Find rssrvpolicy.config . Backup the file before making any changes below. Right click on the file and edit it.
- n the above config file we need to add extract CodeGroup nodes for each ZappySys Driver dll Path which you like to use in SSRS Reports. For demo purpose we have added XML and JSON driver paths you can do more as needed. Basically in SSRS 2012 this may not be needed but in newer version of SSRS (i.e. 2017 and higher) Custom Drivers or Assemblies need Grant to execute under SSRS service. Here is the code you have to add in config file.
1234567891011121314151617181920212223242526272829303132<CodeGroup class="UnionCodeGroup"version="1"PermissionSetName="FullTrust"Name="ZappyOdbcJsonDllFullTrust"Description="Code group for ZappySys JSON Driver - 64bit"><IMembershipCondition class="UrlMembershipCondition"version="1"Url="C:\Program Files (x86)\ZappySys\ZappySys ODBC PowerPack\JsonDriverX64\ZappySys.Odbc.Json.dll"/></CodeGroup><CodeGroup class="UnionCodeGroup"version="1"PermissionSetName="FullTrust"Name="ZappyOdbcXmlDllFullTrust"Description="Code group for ZappySys XML Driver - 64bit"><IMembershipCondition class="UrlMembershipCondition"version="1"Url="C:\Program Files (x86)\ZappySys\ZappySys ODBC PowerPack\XmlDriverX64\ZappySys.Odbc.Xml.dll"/></CodeGroup><!-- to do - add more driver entries here --><CodeGroup class="UnionCodeGroup"version="1"PermissionSetName="FullTrust"Name="ZappyDllFullTrust"Description="Code group for all common ZappySys dlls"><IMembershipCondition class="StrongNameMembershipCondition"version="1"PublicKeyBlob="0024000004800000940000000602000000240000525341310004000001000100c997874c205e00cc82fc09f40f718a6384103bc4a6300abbdcce09a20f554aa82c89e51dbcfaee9c9480dd25ea76d97c2a4562aeb51c169dab3e6be9054edec2aaa994937a670f651fb4037292c535a10cccba9b886c92262424f3ef786f9830acdcb98aff39567e4bf56d304f546239c0d235a4d59497c030891711db4b29cc"/></CodeGroup> - Here is Full rsssrvpolicy.config code in case you like to review. Your file may slightly different so dont just copy full content as is.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203<configuration><mscorlib><security><policy><PolicyLevel version="1"><SecurityClasses><SecurityClass Name="AllMembershipCondition" Description="System.Security.Policy.AllMembershipCondition, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/><SecurityClass Name="AspNetHostingPermission" Description="System.Web.AspNetHostingPermission, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/><SecurityClass Name="DnsPermission" Description="System.Net.DnsPermission, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/><SecurityClass Name="EnvironmentPermission" Description="System.Security.Permissions.EnvironmentPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/><SecurityClass Name="FileIOPermission" Description="System.Security.Permissions.FileIOPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/><SecurityClass Name="FirstMatchCodeGroup" Description="System.Security.Policy.FirstMatchCodeGroup, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/><SecurityClass Name="IsolatedStorageFilePermission" Description="System.Security.Permissions.IsolatedStorageFilePermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/><SecurityClass Name="NamedPermissionSet" Description="System.Security.NamedPermissionSet"/><SecurityClass Name="PrintingPermission" Description="System.Drawing.Printing.PrintingPermission, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/><SecurityClass Name="ReflectionPermission" Description="System.Security.Permissions.ReflectionPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/><SecurityClass Name="RegistryPermission" Description="System.Security.Permissions.RegistryPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/><SecurityClass Name="SecurityPermission" Description="System.Security.Permissions.SecurityPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/><SecurityClass Name="SocketPermission" Description="System.Net.SocketPermission, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/><SecurityClass Name="SqlClientPermission" Description="System.Data.SqlClient.SqlClientPermission, System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/><SecurityClass Name="StrongNameMembershipCondition" Description="System.Security.Policy.StrongNameMembershipCondition, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/><SecurityClass Name="UnionCodeGroup" Description="System.Security.Policy.UnionCodeGroup, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/><SecurityClass Name="UrlMembershipCondition" Description="System.Security.Policy.UrlMembershipCondition, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/><SecurityClass Name="WebPermission" Description="System.Net.WebPermission, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/><SecurityClass Name="ZoneMembershipCondition" Description="System.Security.Policy.ZoneMembershipCondition, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/></SecurityClasses><NamedPermissionSets><PermissionSetclass="NamedPermissionSet"version="1"Unrestricted="true"Name="FullTrust"Description="Allows full access to all resources"/><PermissionSetclass="NamedPermissionSet"version="1"Name="Nothing"Description="Denies all resources, including the right to execute"/><PermissionSetclass="NamedPermissionSet"version="1"Name="Execution"><IPermissionclass="SecurityPermission"version="1"Flags="Execution"/></PermissionSet></NamedPermissionSets><CodeGroupclass="FirstMatchCodeGroup"version="1"PermissionSetName="Nothing"><IMembershipConditionclass="AllMembershipCondition"version="1"/><CodeGroupclass="UnionCodeGroup"version="1"PermissionSetName="Execution"Name="Report_Expressions_Default_Permissions"Description="This code group grants default permissions for code in report expressions and Code element. "><IMembershipConditionclass="StrongNameMembershipCondition"version="1"PublicKeyBlob="0024000004800000940000000602000000240000525341310004000001000100512C8E872E28569E733BCB123794DAB55111A0570B3B3D4DE3794153DEA5EFB7C3FEA9F2D8236CFF320C4FD0EAD5F677880BF6C181F296C751C5F6E65B04D3834C02F792FEE0FE452915D44AFE74A0C27E0D8E4B8D04EC52A8E281E01FF47E7D694E6C7275A09AFCBFD8CC82705A06B20FD6EF61EBBA6873E29C8C0F2CAEDDA2"/></CodeGroup><CodeGroupclass="FirstMatchCodeGroup"version="1"PermissionSetName="Execution"Description="This code group grants MyComputer code Execution permission. "><IMembershipConditionclass="ZoneMembershipCondition"version="1"Zone="MyComputer" /><CodeGroupclass="UnionCodeGroup"version="1"PermissionSetName="FullTrust"Name="Microsoft_Strong_Name"Description="This code group grants code signed with the Microsoft strong name full trust. "><IMembershipConditionclass="StrongNameMembershipCondition"version="1"PublicKeyBlob="002400000480000094000000060200000024000052534131000400000100010007D1FA57C4AED9F0A32E84AA0FAEFD0DE9E8FD6AEC8F87FB03766C834C99921EB23BE79AD9D5DCC1DD9AD236132102900B723CF980957FC4E177108FC607774F29E8320E92EA05ECE4E821C0A5EFE8F1645C4C0C93C1AB99285D622CAA652C1DFAD63D745D6F2DE5F17E5EAF0FC4963D261C8A12436518206DC093344D5AD293"/></CodeGroup><CodeGroupclass="UnionCodeGroup"version="1"PermissionSetName="FullTrust"Name="Ecma_Strong_Name"Description="This code group grants code signed with the ECMA strong name full trust. "><IMembershipConditionclass="StrongNameMembershipCondition"version="1"PublicKeyBlob="00000000000000000400000000000000"/></CodeGroup><CodeGroupclass="UnionCodeGroup"version="1"PermissionSetName="FullTrust"Name="Report_Server_Strong_Name"Description="This code group grants Report Server code full trust. "><IMembershipConditionclass="StrongNameMembershipCondition"version="1"PublicKeyBlob="0024000004800000940000000602000000240000525341310004000001000100272736AD6E5F9586BAC2D531EABC3ACC666C2F8EC879FA94F8F7B0327D2FF2ED523448F83C3D5C5DD2DFC7BC99C5286B2C125117BF5CBE242B9D41750732B2BDFFE649C6EFB8E5526D526FDD130095ECDB7BF210809C6CDAD8824FAA9AC0310AC3CBA2AA0523567B2DFA7FE250B30FACBD62D4EC99B94AC47C7D3B28F1F6E4C8"/></CodeGroup><CodeGroupclass="UnionCodeGroup"version="1"PermissionSetName="FullTrust"><IMembershipConditionclass="UrlMembershipCondition"version="1"Url="$CodeGen$/*"/></CodeGroup><CodeGroupclass="UnionCodeGroup"version="1"PermissionSetName="FullTrust"Name="SharePoint_Server_Strong_Name"Description="This code group grants SharePoint Server code full trust. "><IMembershipConditionclass="StrongNameMembershipCondition"version="1"PublicKeyBlob="0024000004800000940000000602000000240000525341310004000001000100AFD4A0E7724151D5DD52CB23A30DED7C0091CC01CFE94B2BCD85B3F4EEE3C4D8F6417BFF763763A996D6B2DFC1E7C29BCFB8299779DF8785CDE2C168CEEE480E570725F2468E782A9C2401302CF6DC17E119118ED2011937BAE9698357AD21E8B6DFB40475D16E87EB03C744A5D32899A0DBC596A6B2CFA1E509BE5FBD09FACF"/></CodeGroup><CodeGroupclass="UnionCodeGroup"version="1"PermissionSetName="FullTrust"Name="Analisys_Server_Strong_Name"Description="This code group grants DataFeedClient.dll full trust. "><IMembershipConditionclass="StrongNameMembershipCondition"version="1"PublicKeyBlob="0024000004800000940000000602000000240000525341310004000001000100272736AD6E5F9586BAC2D531EABC3ACC666C2F8EC879FA94F8F7B0327D2FF2ED523448F83C3D5C5DD2DFC7BC99C5286B2C125117BF5CBE242B9D41750732B2BDFFE649C6EFB8E5526D526FDD130095ECDB7BF210809C6CDAD8824FAA9AC0310AC3CBA2AA0523567B2DFA7FE250B30FACBD62D4EC99B94AC47C7D3B28F1F6E4C8"/></CodeGroup><CodeGroupclass="UnionCodeGroup"version="1"PermissionSetName="FullTrust"Name="OXML_SDK_Strong_Name"Description="Grants FullTrust to OpenXmlSdk"><IMembershipConditionclass="StrongNameMembershipCondition"version="1"PublicKeyBlob="0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9"/></CodeGroup><CodeGroup class="UnionCodeGroup"version="1"PermissionSetName="FullTrust"Name="ZappyOdbcJsonDllFullTrust"Description="Code group for zappy json processing extension"><IMembershipCondition class="UrlMembershipCondition"version="1"Url="C:\Program Files (x86)\ZappySys\ZappySys ODBC PowerPack\JsonDriverX64\ZappySys.Odbc.Json.dll"/></CodeGroup><CodeGroup class="UnionCodeGroup"version="1"PermissionSetName="FullTrust"Name="ZappyOdbcXmlDllFullTrust"Description="Code group for zappy json processing extension"><IMembershipCondition class="UrlMembershipCondition"version="1"Url="C:\Program Files (x86)\ZappySys\ZappySys ODBC PowerPack\XmlDriverX64\ZappySys.Odbc.Xml.dll"/></CodeGroup><!-- to do - add more driver entries here --><CodeGroup class="UnionCodeGroup"version="1"PermissionSetName="FullTrust"Name="ZappyDllFullTrust"Description="Code group for all zappy dlls"><IMembershipCondition class="StrongNameMembershipCondition"version="1"PublicKeyBlob="0024000004800000940000000602000000240000525341310004000001000100c997874c205e00cc82fc09f40f718a6384103bc4a6300abbdcce09a20f554aa82c89e51dbcfaee9c9480dd25ea76d97c2a4562aeb51c169dab3e6be9054edec2aaa994937a670f651fb4037292c535a10cccba9b886c92262424f3ef786f9830acdcb98aff39567e4bf56d304f546239c0d235a4d59497c030891711db4b29cc"/></CodeGroup></CodeGroup></CodeGroup></PolicyLevel></policy></security></mscorlib></configuration> - Thats it now Restart SSRS Service after above change and you should be fine. If you still face the issue we suggest you use Data Gateway approach.
Conclusion
To conclude, we can say that it is now easy to get JSON and REST API data in SSRS. We only need to download the ZappySys ODBC PowerPack and we will be able to access the data.
Furthermore, you learned how to work with parameters (Dynamic Queries), with dates and pass parameters to URL.
References
Finally, for more information about how to read REST API using SSRS you can check the following links:
⦁ Category Archives: ODBC PowerPack
⦁ Develop with the REST APIs for Reporting Services
⦁ Facebook Graph API
Keywords: SSRS JSON data source, SSRS REST API data source, SSRS SOAP Web Service data source, Call REST API in SSRS, Load JSON into SSRS, Read REST API in SSRS, Read XML SOAP Web Service in SSRS, Read JSON file in SSRS,
Read XML file in SSRS