Post Import

 

Updated: November 13, 2017



Request | Response

The Post Import operation creates content from a PBIX file.

Note To call this operation, an app token or key is required. To learn more, see Authenticating and authorizing with Power BI Workspace Collections.

POST https://api.powerbi.com/v1.0/collections/{collectionName}/workspaces/{workspaceId}/imports

Uri parameter

NameTypeDescriptionValues
collectionName (required)StringThe workspace collection name
workspaceId (required)StringThe workspace id
datasetDisplayName (required)StringWhen using a PBIX or Excel file, setting this parameter will override the default name of the dataset.A Dataset name.
nameConflictStringIf datasetDisplayName is provided, determines what to do if a Dataset with the same name exists. Otherwise, determines what to do if the Dataset is already imported.- Ignore (default)
- Abort
- Overwrite
PreferClientRoutingStringUse this parameter to avoid the request redirecting between clusters and to avoid timeout errors.- true
- false (default)

Header

Content-Type: multipart/form-data; boundary ----------BOUNDARY Authorization: AppToken

Body

----------BOUNDARY Content-Disposition: form-data; filename="{pbix file}.pbix" Content-Type: application / octet – stream

NOTE

Status code

CodeDescription
200OK. Indicates success. An JSON object which represents list of Import objects.
307Message should be forwarded. The location to forward is in the Response Location Header.

Content-Type

application/json

Body schema

{  
"@odata.context": "https://api.powerbi.com/v1.0/collections/{collectionName}/workspaces/{workspaceId}/imports",  
  Import{  
                id: string  
                name:string  
                importState:string  
                reports:[undefined]  

               datasets: [  
                Dataset {  
                    id:string  
                    name:string *  
                    defaultRetentionPolicy: string  
                    tables: [  
                        Table {  
                            name:string  
                                columns:[  
                                    Column {  
                                        name:string *  
                                        dataType:string *  
                                            }  
                                        ]  
                                rows:[  
                                    Row {  
                                        id: string  
                                        }  
                                    ]  
                                }  
                            ]  
                    webUrl: string  
                    datasources:[  
                            Datasource {  
                                    name: string  
                                    connectionString: string  
                                        }  
                                ]  
                    }  
                    ]  
                }  
}  

NOTE To use this sample you will need a PBIX file to import into PowerBI. If you don't have a PBIX file handy, you can download the Retail Analysis Sample PBIX.

using System;
using System.Net;
using System.IO;

namespace PBIGettingStarted
{
    class Program
    {
        //Access key for app token
        private static string accessKey = "{access-key}";

        //Power BI app token values
        private static string workspaceCollectionName = "workspace-name";
        private static string workspaceId = "workspace-id";

        private static string pbixFileName = "AdventureWorks.pbix";

        static void Main(string[] args)
        {
            //Imports uri
            var uri = String.Format
                ("https://api.powerbi.com/v1.0/collections/{0}/workspaces/{1}/imports?datasetDisplayName=SampleImport", 
                workspaceCollectionName, workspaceId);
            
            //PBIX file to import
            DirectoryInfo di = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);
            string fileName = string.Format(@"{0}\{1}", di.Parent.Parent.FullName, pbixFileName);
          
            //Get an app token to generate a JSON Web Token (JWT). An app token flow is a claims-based design pattern.
            //To learn how you can code an app token flow to generate a JWT, see the PowerBIToken class.
            var appToken = PowerBIToken.CreateDevToken(workspaceCollectionName, workspaceId);

            //After you get a PowerBIToken which has Claims including your WorkspaceName and WorkspaceID,
            //you generate JSON Web Token (JWT) . The Generate() method uses classes from System.IdentityModel.Tokens: SigningCredentials, 
            //JwtSecurityToken, and JwtSecurityTokenHandler. 
            string jwt = appToken.Generate(accessKey);

            //Create web request
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);

            //Import Request format:
            // Header:
            //  Content - Type: multipart / form - data; ----------BOUNDARY
            //  Authorization: AppToken

            // Body:
            //  ----------BOUNDARY
            //  Content - Disposition: form - data; filename = "{pbix file}.pbix"
            //  Content - Type: application / octet – stream

            //Define POST
            request.Method = "POST";

            //Header
            // Boundary
            string boundary = "----------BOUNDARY";
            byte[] boundaryBytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

            // Content - Type
            request.ContentType = "multipart/form-data; boundary=" + boundary;

            // Authorization - Use AppToken jwt for Authorization header
            request.Headers.Add("Authorization", String.Format("AppToken {0}", jwt));

            //Body
            string bodyTemplate = "Content-Disposition: form-data; filename=\"{0}\"\r\nContent-Type: application / octet - stream\r\n\r\n";
            string body = string.Format(bodyTemplate, fileName);
            byte[] bodyBytes = System.Text.Encoding.UTF8.GetBytes(body);

            //Get request stream 
            using (Stream rs = request.GetRequestStream())
            {
                rs.Write(boundaryBytes, 0, boundaryBytes.Length);
                rs.Write(bodyBytes, 0, bodyBytes.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);
            }

            //Get response
            using (HttpWebResponse response = request.GetResponse() as System.Net.HttpWebResponse)
            {
                //If Import succeeds, StatusCode = Accepted 
                var responseStatusCode = response.StatusCode.ToString();
            }
        }
    }
}


PowerBIToken

using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens;
using System.Security.Claims;
using System.Text;

namespace PBIGettingStarted
{
    /// <summary>
    /// The Power BI app token used to authenticate with Power BI Embedded services
    /// </summary>
    public class PowerBIToken
    {
        private const int DefaultExpirationSeconds = 3600;
        private const string DefaultIssuer = "PowerBISDK";
        private const string DefaultAudience = "https://analysis.windows.net/powerbi/api";

        /// <summary>
        /// The token issuer
        /// </summary>
        public string Issuer { get; set; }

        /// <summary>
        /// The audience this token is valid for
        /// </summary>
        public string Audience { get; set; }

        /// <summary>
        /// Gets or sets a collection of claims associated with this token
        /// </summary>
        public ICollection<Claim> Claims { get; private set; }

        /// <summary>
        /// Gets or set the access key used to sign the app token
        /// </summary>
        public string AccessKey { get; set; }

        /// <summary>
        /// Gets or sets the token expiration.  Default expiration is 1 hour
        /// </summary>
        public DateTime? Expiration { get; set; }

        /// <summary>
        /// The Power BI supported claim types
        /// </summary>
        public static class ClaimTypes
        {
            /// <summary>
            /// The version claim
            /// </summary>
            public const string Version = "ver";
            /// <summary>
            /// The token type claim
            /// </summary>
            public const string Type = "type";
            /// <summary>
            /// The workspace collection claim
            /// </summary>
            public const string WorkspaceCollectionName = "wcn";
            /// <summary>
            /// The workspace id claim
            /// </summary>
            public const string WorkspaceId = "wid";
            /// <summary>
            /// The report id claim
            /// </summary>
            public const string ReportId = "rid";
        }


        /// <summary>
        /// Represents an access token used to authenticate and authorize against Power BI Platform services
        /// </summary>
        public PowerBIToken()
        {
            this.Claims = new List<Claim>();
            this.Claims.Add(new Claim(ClaimTypes.Version, "0.1.0"));
            this.Issuer = DefaultIssuer;
            this.Audience = DefaultAudience;
            this.Expiration = DateTime.UtcNow.AddSeconds(DefaultExpirationSeconds);
        }

        /// <summary>
        /// Create a developer token with default expiration used to access Power BI platform services
        /// </summary>
        /// <param name="workspaceCollectionName">The workspace collection name</param>
        /// <param name="workspaceId">The workspace id</param>
        /// <param name="expiration">The token expiration date/time</param>
        /// <returns>The Power BI access token</returns>
        public static PowerBIToken CreateDevToken(string workspaceCollectionName, string workspaceId)
        {

            var token = new PowerBIToken
            {
                Expiration = DateTime.UtcNow.Add(TimeSpan.FromSeconds(DefaultExpirationSeconds))
            };

            token.Claims.Add(new Claim(ClaimTypes.Type, "dev"));
            token.Claims.Add(new Claim(ClaimTypes.WorkspaceCollectionName, workspaceCollectionName));
            token.Claims.Add(new Claim(ClaimTypes.WorkspaceId, workspaceId));

            return token;
        }

        /// <summary>
        /// Create a embed token with default expiration used to embed Power BI components into your own applications
        /// </summary>
        /// <param name="workspaceCollectionName">The workspace collection name</param>
        /// <param name="workspaceId">The workspace id</param>
        /// <param name="reportId">The report id</param>
        /// <param name="expiration">The token expiration date/time</param>
        /// <returns>The Power BI access token</returns>
        public static PowerBIToken CreateReportEmbedToken(string workspaceCollectionName, string workspaceId, string reportId)
        {
            var token = new PowerBIToken
            {
                Expiration = DateTime.UtcNow.Add(TimeSpan.FromSeconds(DefaultExpirationSeconds))
            };

            token.Claims.Add(new Claim(ClaimTypes.Type, "embed"));
            token.Claims.Add(new Claim(ClaimTypes.WorkspaceCollectionName, workspaceCollectionName));
            token.Claims.Add(new Claim(ClaimTypes.WorkspaceId, workspaceId));
            token.Claims.Add(new Claim(ClaimTypes.ReportId, reportId));

            return token;
        }

        /// <summary>
        /// Generates an app token with the specified claims and signs it the the configured signing key.
        /// </summary>
        /// <param name="accessKey">The access key used to sign the app token</param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException"></exception>
        public string Generate(string accessKey = null)
        {
            if (string.IsNullOrWhiteSpace(this.AccessKey) && accessKey == null)
            {
                throw new ArgumentNullException(nameof(accessKey));
            }

            accessKey = accessKey ?? this.AccessKey;

            var key = Encoding.UTF8.GetBytes(accessKey);
            var signingCredentials = new SigningCredentials(new InMemorySymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature, SecurityAlgorithms.Sha256Digest);
            var token = new JwtSecurityToken(this.Issuer, this.Audience, this.Claims, DateTime.UtcNow, this.Expiration, signingCredentials);

            return new JwtSecurityTokenHandler().WriteToken(token);
        }

    }
}

Show: