<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:taxo="http://purl.org/rss/1.0/modules/taxonomy/" version="2.0">
  <channel>
    <title>topic Re: API Import 400 Bad Request Error when uploading pbix file in Developer</title>
    <link>https://community.fabric.microsoft.com/t5/Developer/API-Import-400-Bad-Request-Error-when-uploading-pbix-file/m-p/234515#M7389</link>
    <description>Yea, i ended up figuring that out late today. Sorry for not updating the thread. I appreciate all your help. I wpuld have struggled a lot more than I did without it.</description>
    <pubDate>Sat, 19 Aug 2017 06:02:57 GMT</pubDate>
    <dc:creator>Anonymous</dc:creator>
    <dc:date>2017-08-19T06:02:57Z</dc:date>
    <item>
      <title>API Import 400 Bad Request Error when uploading pbix file</title>
      <link>https://community.fabric.microsoft.com/t5/Developer/API-Import-400-Bad-Request-Error-when-uploading-pbix-file/m-p/232628#M7333</link>
      <description>&lt;P&gt;Hello,&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;I have an application where we want to show PowerBI Premium reports in our application. &amp;nbsp;However, before that happens, we also need to upload PBIX reports using our application. &amp;nbsp;I have been able to get the proper token, and when I run any get requests (like GetReports), on the API, I get the data back just fine.&amp;nbsp;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;However, when I run an Import on the api, it always says 400 Error Bad Request. &amp;nbsp;I am going to post my code below and would love any help I could get. &amp;nbsp;I have tried reading in the file from disk, instead of passing it in using FileSelctor tool, I have tried uising different types of requests, made sure I have all permissions assigned to my app through Azure Portal, ect... and nothing has worked. Pretty much I have exausted my thoughts on how to proceed, &amp;nbsp;It is just strange that every read seems to work great, but a post will not. &amp;nbsp;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;All the setup seems to be in place. The only setup I have not done is create Workspace Collections in Azure. The reason for this is it was my understanding that this was part of the old embeded style. &amp;nbsp;I do have a new AppWorkspace that was created using my Premium account in PowerBI itself. &amp;nbsp;Not sure if this has something to do with why an import is not working or what, but wanted to give as much info as possible so I can get help ASAP.&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;Thank you all very much, and I look forward to hearing back from you.&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;Steven&amp;nbsp;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;PRE&gt;public async Task Upload([FromUri] int ReportId, [FromUri] string reportName, [FromUri] bool overwrite)
        {
            try
            {

                if (!Request.Content.IsMimeMultipartContent("form-data"))
                {
                    throw new HttpResponseException(HttpStatusCode.BadRequest);
                }

                var provider = await Request.Content.ReadAsMultipartAsync&amp;lt;InMemoryMultipartFormDataStreamProvider&amp;gt;(new InMemoryMultipartFormDataStreamProvider());

                //access form data
                NameValueCollection formData = provider.FormData;

                //access files
                IList&amp;lt;HttpContent&amp;gt; files = provider.Files;
                //Example: reading a file's stream like below
                HttpContent file1 = files[0];
               // Stream file1Stream = await file1.ReadAsStreamAsync();

                byte[] fileToSend = await file1.ReadAsByteArrayAsync();

                // Create a user password cradentials.
                var credential = new UserCredential(Username, Password);
                
// Authenticate using created credentials
                var authenticationContext = new AuthenticationContext(AuthorityUrl);
                var authenticationResult = await authenticationContext.AcquireTokenAsync(ResourceUrl, ClientId2, credential);
                token = authenticationResult.AccessToken;
                var tokenCredentials = new TokenCredentials(authenticationResult.AccessToken, "Bearer");
                
                var nameConflict = "Overwrite";
                string responseContent = string.Empty;

                //Configure dashboards request
                System.Net.WebRequest request = System.Net.WebRequest.Create("https://api.powerbi.com/v1.0/myorg/imports?datasetDisplayName=TestImport&amp;amp;nameConflict=Overwrite") as System.Net.HttpWebRequest;
                request.Method = "POST";
                
// Set the content type of the data being posted.
                request.ContentType = "multipart/form-data";

                // Set the content length of the string being posted.
                request.ContentLength = fileToSend.Length;
                request.Headers.Add("Authorization", String.Format("Bearer {0}", token));

                using (Stream requestStream = request.GetRequestStream())
                {
                    requestStream.Write(fileToSend, 0, fileToSend.Length);
                    requestStream.Close();
                }

                //Get dashboards response from request.GetResponse()
                using (var response = request.GetResponse() as System.Net.HttpWebResponse)
                {
                    //Get reader from response stream
                    using (var reader = new System.IO.StreamReader(response.GetResponseStream()))
                    {
                        responseContent = reader.ReadToEnd();
                    }
                }
            }
            catch (Exception ex)
            {
                var junk = true;
            }
        }
    }&lt;/PRE&gt;</description>
      <pubDate>Wed, 16 Aug 2017 17:13:30 GMT</pubDate>
      <guid>https://community.fabric.microsoft.com/t5/Developer/API-Import-400-Bad-Request-Error-when-uploading-pbix-file/m-p/232628#M7333</guid>
      <dc:creator>Anonymous</dc:creator>
      <dc:date>2017-08-16T17:13:30Z</dc:date>
    </item>
    <item>
      <title>Re: API Import 400 Bad Request Error when uploading pbix file</title>
      <link>https://community.fabric.microsoft.com/t5/Developer/API-Import-400-Bad-Request-Error-when-uploading-pbix-file/m-p/232937#M7342</link>
      <description>&lt;P&gt;@Anonymous&lt;/a&gt;&lt;/P&gt;
&lt;P&gt;I see you are appending the nameConflict parameter to the URL, one most probably reason I can think of for your 400 error&amp;nbsp;is that the url with nameConflict parameter would throw error if the report you'd like to import doesn't already exist.&amp;nbsp;&lt;/P&gt;
&lt;PRE&gt;https://api.powerbi.com/v1.0/myorg/imports?datasetDisplayName=TestImport&amp;amp;&lt;STRONG&gt;nameConflict=Overwrite&lt;/STRONG&gt;&lt;/PRE&gt;
&lt;P&gt;By the way, I don't find /groups/{groupid} in the URL. Do note the that you can only embed the reports from a created app workspace.&lt;/P&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;For better troubleshooting, I'd suggest you add an extra catch block.&lt;/P&gt;
&lt;PRE&gt;catch (WebException wex)
            {
                if (wex.Response != null)
                {
                    using (var errorResponse = (HttpWebResponse)wex.Response)
                    {
                        using (var reader = new StreamReader(errorResponse.GetResponseStream()))
                        {
                            string errorString = reader.ReadToEnd();
                            dynamic respJson = JsonConvert.DeserializeObject&amp;lt;dynamic&amp;gt;(errorString);
                            Console.WriteLine(respJson.ToString());
                            //TODO: use JSON.net to parse this string and look at the error message
                        }
                    }
                }
            }&lt;/PRE&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;Also you can reference my import pbix file demo.&lt;/P&gt;
&lt;PRE&gt;using System;
using System.Net;
//Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory -Version 2.21.301221612
using Microsoft.IdentityModel.Clients.ActiveDirectory;

//Install-Package Newtonsoft.Json 
using Newtonsoft.Json;
using System.IO;
using System.Threading.Tasks;

namespace ConsoleApplication39
{

    class Program
    {

        //Step 1 - Replace {client id} with your client app ID. 
        //To learn how to get a client app ID, see Register a client app (https://msdn.microsoft.com/en-US/library/dn877542.aspx#clientID)
        private static string clientID = "&lt;STRONG&gt;{client id}&lt;/STRONG&gt;";
          
        //Resource Uri for Power BI API
        private static string resourceUri = "https://analysis.windows.net/powerbi/api";

        //OAuth2 authority Uri
        private static string authorityUri = "https://login.windows.net/common/oauth2/authorize";
         
        private static string token = String.Empty;

        //Uri for Power BI datasets
        private static string pbiEndpoint = "https://api.powerbi.com/v1.0/myorg"; 

        //Example dataset name and group name 
        private static string groupId = "&lt;STRONG&gt;{group id}&lt;/STRONG&gt;";

        static void Main(string[] args)
        {
            //Import sample 
            string pbixPath = @"C:\test\KPI.pbix";
            string datasetDisplayName = "mydataset";

            Task t = Import(string.Format("{0}/groups/{1}/imports?datasetDisplayName={2}&amp;amp;nameConflict=Overwrite", pbiEndpoint, groupId, datasetDisplayName), pbixPath);
            t.Wait();

            Console.ReadKey();

        }

        public static async Task&amp;lt;string&amp;gt; Import(string url, string fileName)
        {
            string responseStatusCode = string.Empty;

            string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
            byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            request.ContentType = "multipart/form-data; boundary=" + boundary;
            request.Method = "POST";
            request.KeepAlive = true;

            var credential = new UserCredential(&lt;STRONG&gt;yourPbiAccount&lt;/STRONG&gt;, &lt;STRONG&gt;Password&lt;/STRONG&gt;);

            // Authenticate using created credentials
            var authenticationContext = new AuthenticationContext(authorityUri);
            var authenticationResult = await authenticationContext.AcquireTokenAsync(resourceUri, clientID, credential);
            token = authenticationResult.AccessToken;


            request.Headers.Add("Authorization", String.Format("Bearer {0}", token.ToString()));

            using (Stream rs = request.GetRequestStream())
            {
                rs.Write(boundarybytes, 0, boundarybytes.Length);

                string headerTemplate = "Content-Disposition: form-data; filename=\"{0}\"\r\nContent-Type: application / octet - stream\r\n\r\n";
                string header = string.Format(headerTemplate, fileName);
                byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
                rs.Write(headerbytes, 0, headerbytes.Length);

                using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                {
                    byte[] buffer = new byte[4096];
                    int bytesRead = 0;
                    while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        rs.Write(buffer, 0, bytesRead);
                    }
                }

                byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
                rs.Write(trailer, 0, trailer.Length);
            }
            try
           {
                using (HttpWebResponse response = request.GetResponse() as System.Net.HttpWebResponse)
                {
                    responseStatusCode = response.StatusCode.ToString();

                    Console.WriteLine("Import pbix file is {0}", responseStatusCode);
                }
            }
            catch (WebException wex)
            {
                if (wex.Response != null)
                {
                    using (var errorResponse = (HttpWebResponse)wex.Response)
                    {
                        using (var reader = new StreamReader(errorResponse.GetResponseStream()))
                        {
                            string errorString = reader.ReadToEnd();
                            dynamic respJson = JsonConvert.DeserializeObject&amp;lt;dynamic&amp;gt;(errorString);
                            Console.WriteLine(respJson.ToString());
                            //TODO: use JSON.net to parse this string and look at the error message
                        }
                    }
                }
            } 

            return responseStatusCode;
        }
         
    }
}
&lt;/PRE&gt;
&lt;P&gt;&amp;nbsp;&lt;/P&gt;</description>
      <pubDate>Thu, 17 Aug 2017 05:49:31 GMT</pubDate>
      <guid>https://community.fabric.microsoft.com/t5/Developer/API-Import-400-Bad-Request-Error-when-uploading-pbix-file/m-p/232937#M7342</guid>
      <dc:creator>Eric_Zhang</dc:creator>
      <dc:date>2017-08-17T05:49:31Z</dc:date>
    </item>
    <item>
      <title>Re: API Import 400 Bad Request Error when uploading pbix file</title>
      <link>https://community.fabric.microsoft.com/t5/Developer/API-Import-400-Bad-Request-Error-when-uploading-pbix-file/m-p/233627#M7358</link>
      <description>&lt;P&gt;&lt;a href="https://community.fabric.microsoft.com/t5/user/viewprofilepage/user-id/6971"&gt;@Eric_Zhang&lt;/a&gt;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;I apprecaite your response and am sorry I did not get back to you earlier. &amp;nbsp;I decided for the time being to work on the front end stuff and get the PowerBI reports to show up in the app. &amp;nbsp;I have pretty much finished that now, and am going back to finalizing the import. &amp;nbsp;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;I tried your below code, and and was still getting an error as I had deleted the uploaded report and thus removed the part about overwritting the data from the end of the url. &amp;nbsp;This broke. &amp;nbsp;But when I put that back on, it all seems to have worked great. &amp;nbsp;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;With that said though, I have 2 last questions. &amp;nbsp;What if I already had the file in memory, and did not want to save it locally? &amp;nbsp;In my app I use a tool that finds the tile and in the web request I get the file. I can convert this to byets or a stream, but I am confused as to what would go in these lines then....&lt;BR /&gt;&lt;BR /&gt;&lt;/P&gt;&lt;PRE&gt;string headerTemplate = "Content-Disposition: form-data; filename=\"{0}\"\r\nContent-Type: application / octet - stream\r\n\r\n";
                string header = string.Format(headerTemplate, fileName);&lt;/PRE&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;Secondly, &amp;nbsp;is the only way to know if said report already exists to check call the API to get the reports and check to see if one with that name already exists? &amp;nbsp;I ask because it seems to me that I need to modify the URL depnding on if the report exists previously or not. &amp;nbsp; So is that the best way to handel this, since you said having the overwirte and dataSetDisplayName&amp;nbsp;on the URL if the report does not exist throws an error?&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;Either.....&lt;BR /&gt;&lt;BR /&gt;&lt;/P&gt;&lt;PRE&gt;string.Format("{0}/groups/{1}/imports?datasetDisplayName={2}&amp;amp;nameConflict=Overwrite", pbiEndpoint, groupId, datasetDisplayName), pbixPath&lt;/PRE&gt;&lt;P&gt;OR&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;PRE&gt;string.Format("{0}/groups/{1}/imports?", pbiEndpoint, groupId), pbixPath&lt;/PRE&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;Thanks a ton.&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;Stizz001&lt;/P&gt;</description>
      <pubDate>Thu, 17 Aug 2017 21:07:30 GMT</pubDate>
      <guid>https://community.fabric.microsoft.com/t5/Developer/API-Import-400-Bad-Request-Error-when-uploading-pbix-file/m-p/233627#M7358</guid>
      <dc:creator>Anonymous</dc:creator>
      <dc:date>2017-08-17T21:07:30Z</dc:date>
    </item>
    <item>
      <title>Re: API Import 400 Bad Request Error when uploading pbix file</title>
      <link>https://community.fabric.microsoft.com/t5/Developer/API-Import-400-Bad-Request-Error-when-uploading-pbix-file/m-p/234322#M7381</link>
      <description>&lt;P&gt;&lt;a href="https://community.fabric.microsoft.com/t5/user/viewprofilepage/user-id/6971"&gt;@Eric_Zhang&lt;/a&gt;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;When I try to upload a file that previously exists using the URL with ?datasetDisplayName={2}&amp;amp;nameConflict=Overwrite at the end, it works great. &amp;nbsp;However when the report is a new report, and I try to upload it using...&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;&lt;A href="https://api.powerbi.com/v1.0/myorg/groups/{GroupID}/imports" target="_blank"&gt;https://api.powerbi.com/v1.0/myorg/groups/{GroupID}/imports&lt;/A&gt;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;It does not update. &amp;nbsp;In the code that you gave me to catch the error, all I see is the word Message: "". &amp;nbsp;It does not tell me anything more. Previously you said that if you try to import a report, that does not exist, and use the&amp;nbsp;&lt;SPAN&gt;?datasetDisplayName={2}&amp;amp;nameConflict=Overwrite at end of URL, that it will not work. &amp;nbsp;Well it seems even without that it does not work. Any thoughts why?&lt;/SPAN&gt;&lt;/P&gt;&lt;P&gt;&lt;SPAN&gt;&lt;BR /&gt;Thanks,&lt;/SPAN&gt;&lt;/P&gt;&lt;P&gt;&lt;SPAN&gt;&lt;BR /&gt;Stizz001&lt;/SPAN&gt;&lt;/P&gt;</description>
      <pubDate>Fri, 18 Aug 2017 16:30:03 GMT</pubDate>
      <guid>https://community.fabric.microsoft.com/t5/Developer/API-Import-400-Bad-Request-Error-when-uploading-pbix-file/m-p/234322#M7381</guid>
      <dc:creator>Anonymous</dc:creator>
      <dc:date>2017-08-18T16:30:03Z</dc:date>
    </item>
    <item>
      <title>Re: API Import 400 Bad Request Error when uploading pbix file</title>
      <link>https://community.fabric.microsoft.com/t5/Developer/API-Import-400-Bad-Request-Error-when-uploading-pbix-file/m-p/234514#M7388</link>
      <description>&lt;P&gt;For new reports just remove the name conflict parameter&amp;nbsp;&lt;/P&gt;</description>
      <pubDate>Sat, 19 Aug 2017 05:52:23 GMT</pubDate>
      <guid>https://community.fabric.microsoft.com/t5/Developer/API-Import-400-Bad-Request-Error-when-uploading-pbix-file/m-p/234514#M7388</guid>
      <dc:creator>brenkehoe</dc:creator>
      <dc:date>2017-08-19T05:52:23Z</dc:date>
    </item>
    <item>
      <title>Re: API Import 400 Bad Request Error when uploading pbix file</title>
      <link>https://community.fabric.microsoft.com/t5/Developer/API-Import-400-Bad-Request-Error-when-uploading-pbix-file/m-p/234515#M7389</link>
      <description>Yea, i ended up figuring that out late today. Sorry for not updating the thread. I appreciate all your help. I wpuld have struggled a lot more than I did without it.</description>
      <pubDate>Sat, 19 Aug 2017 06:02:57 GMT</pubDate>
      <guid>https://community.fabric.microsoft.com/t5/Developer/API-Import-400-Bad-Request-Error-when-uploading-pbix-file/m-p/234515#M7389</guid>
      <dc:creator>Anonymous</dc:creator>
      <dc:date>2017-08-19T06:02:57Z</dc:date>
    </item>
    <item>
      <title>Re: API Import 400 Bad Request Error when uploading pbix file</title>
      <link>https://community.fabric.microsoft.com/t5/Developer/API-Import-400-Bad-Request-Error-when-uploading-pbix-file/m-p/296598#M8732</link>
      <description>&lt;P&gt;Hi&amp;nbsp;@Anonymous&lt;/a&gt;&amp;nbsp;,&amp;nbsp;&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;I am getting &amp;lt;Response [400]&amp;gt;,&amp;nbsp;when I run&amp;nbsp;this code. Any idea what is wrong ?&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;P&gt;Thanks in advance.&lt;/P&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;&lt;PRE&gt;&lt;SPAN&gt;import &lt;/SPAN&gt;requests&lt;BR /&gt;&lt;BR /&gt;values = &lt;SPAN&gt;"""&lt;BR /&gt;&lt;/SPAN&gt;&lt;SPAN&gt;-----BOUNDARY&lt;BR /&gt;&lt;/SPAN&gt;&lt;SPAN&gt;Content-Disposition: form-data; name="mypbix"; filename="mypbix.pbix"&lt;BR /&gt;&lt;/SPAN&gt;&lt;SPAN&gt;Content-Type: application/octet-stream&lt;BR /&gt;&lt;/SPAN&gt;&lt;SPAN&gt;Content-Transfer-Encoding: base64&lt;BR /&gt;&lt;/SPAN&gt;&lt;SPAN&gt;&lt;BR /&gt;&lt;/SPAN&gt;&lt;SPAN&gt;{PBIX binary data}&lt;BR /&gt;&lt;/SPAN&gt;&lt;SPAN&gt;-----BOUNDARY"""&lt;BR /&gt;&lt;/SPAN&gt;&lt;SPAN&gt;&lt;BR /&gt;&lt;/SPAN&gt;headers = {&lt;BR /&gt;  &lt;SPAN&gt;'Content-Type'&lt;/SPAN&gt;: &lt;SPAN&gt;'multipart/form-data; boundary=---BOUNDARY'&lt;/SPAN&gt;,&lt;BR /&gt;  &lt;SPAN&gt;'Authorization'&lt;/SPAN&gt;: &lt;SPAN&gt;'Bearer &amp;lt;access_token&amp;gt;'&lt;BR /&gt;&lt;/SPAN&gt;}&lt;BR /&gt;request = requests.post(&lt;SPAN&gt;'https://api.powerbi.com/v1.0/myorg/groups/&amp;lt;group_id&amp;gt;/imports?datasetDisplayName=ProductOrder'&lt;/SPAN&gt;, &lt;SPAN&gt;data&lt;/SPAN&gt;=values, &lt;SPAN&gt;headers&lt;/SPAN&gt;=headers)&lt;BR /&gt;&lt;SPAN&gt;&lt;BR /&gt;&lt;/SPAN&gt;&lt;/PRE&gt;&lt;P&gt;&amp;nbsp;&lt;/P&gt;</description>
      <pubDate>Sun, 05 Nov 2017 18:55:27 GMT</pubDate>
      <guid>https://community.fabric.microsoft.com/t5/Developer/API-Import-400-Bad-Request-Error-when-uploading-pbix-file/m-p/296598#M8732</guid>
      <dc:creator>ddavid</dc:creator>
      <dc:date>2017-11-05T18:55:27Z</dc:date>
    </item>
  </channel>
</rss>

