how to create and printing label from our application using FedEx api in asp.net?
Categories:
Integrating FedEx API for Label Creation and Printing in ASP.NET

Learn how to integrate the FedEx API into your ASP.NET application to generate and print shipping labels programmatically, streamlining your shipping process.
Integrating with third-party shipping carriers like FedEx is a common requirement for e-commerce and logistics applications. This guide will walk you through the process of using the FedEx API to create and print shipping labels directly from your ASP.NET application. We'll cover the essential steps, from setting up your development environment to making API calls and handling responses.
Understanding the FedEx API and Prerequisites
Before diving into code, it's crucial to understand the FedEx API landscape. FedEx offers various web services for different functionalities, including Rate, Ship, Track, and Address Validation. For label creation, you'll primarily interact with the Ship Service. You'll need to register for a FedEx Developer Account to obtain your developer credentials (Key, Password, Account Number, Meter Number). These credentials are vital for authenticating your API requests.
FedEx provides WSDL files for their web services, which can be consumed in .NET applications to generate proxy classes. These classes simplify the interaction with the SOAP-based API. Ensure you have a stable internet connection and access to the FedEx Developer Resource Center for the latest WSDLs and documentation.
flowchart TD A[Start] --> B{Register for FedEx Developer Account} B --> C[Obtain Credentials (Key, Password, Account, Meter)] C --> D[Download FedEx WSDL Files] D --> E[Add Web Reference/Service Reference in ASP.NET] E --> F[Configure API Request Objects] F --> G[Call FedEx Ship Service] G --> H{API Response Successful?} H -- Yes --> I[Parse Label Data (Base64)] I --> J[Convert to Image/PDF] J --> K[Print Label] H -- No --> L[Handle Errors] K --> M[End] L --> M
High-level process for FedEx label creation and printing
Setting Up Your ASP.NET Project
To begin, create a new ASP.NET Web Application (or add to an existing one). The primary step is to add a Service Reference to the FedEx Ship Service WSDL. This will generate the necessary proxy classes that allow you to interact with the FedEx API as if they were local objects.
- Add Service Reference: In Solution Explorer, right-click on your project, select 'Add' > 'Service Reference...'.
- Address: Enter the URL to the FedEx Ship Service WSDL (e.g.,
https://wsbeta.fedex.com:443/web-services/ship
for testing, orhttps://ws.fedex.com:443/web-services/ship
for production). - Namespace: Provide a meaningful namespace, such as
FedExShipService
. - Configure
web.config
: The service reference will automatically add configuration entries to yourweb.config
file, including endpoint addresses and binding information. You might need to adjust timeout settings for potentially long-running API calls.
<!-- Example web.config snippet for FedEx Service Reference -->
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="ShipServiceSoapBinding" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<security mode="Transport" />
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="https://wsbeta.fedex.com:443/web-services/ship" binding="basicHttpBinding" bindingConfiguration="ShipServiceSoapBinding" contract="FedExShipService.ShipPortType" name="ShipServicePort" />
</client>
</system.serviceModel>
Example web.config
configuration for FedEx Ship Service.
Constructing the Ship Request and Calling the API
The core of label creation involves building a ProcessShipmentRequest
object. This object contains all the details about the shipment, including sender and recipient addresses, package dimensions, weight, service type, and most importantly, the label specification. You'll need to populate various sub-objects within the request.
Key components of the ProcessShipmentRequest
:
WebAuthenticationDetail
: Your FedEx developer key and password.ClientDetail
: Your FedEx account number and meter number.TransactionDetail
: Optional, for tracking your requests.Version
: The API version you are using.RequestedShipment
: This is the most complex part, containing:ShipTimestamp
DropoffType
ServiceType
PackagingType
Shipper
(your address and contact info)Recipient
(customer's address and contact info)ShippingChargesPayment
(payment details)LabelSpecification
(format, type, image type of the label)RequestedPackageLineItems
(details for each package: weight, dimensions, tracking ID type).
using FedExShipService;
using System;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
public class FedExLabelGenerator
{
private const string DeveloperKey = "YOUR_DEVELOPER_KEY";
private const string DeveloperPassword = "YOUR_DEVELOPER_PASSWORD";
private const string AccountNumber = "YOUR_ACCOUNT_NUMBER";
private const string MeterNumber = "YOUR_METER_NUMBER";
public byte[] CreateAndPrintLabel(ShipmentDetails details)
{
ShipPortTypeClient client = new ShipPortTypeClient();
ProcessShipmentRequest request = new ProcessShipmentRequest();
// WebAuthenticationDetail
request.WebAuthenticationDetail = new WebAuthenticationDetail
{
UserCredential = new WebAuthenticationCredential
{
Key = DeveloperKey,
Password = DeveloperPassword
}
};
// ClientDetail
request.ClientDetail = new ClientDetail
{
AccountNumber = AccountNumber,
MeterNumber = MeterNumber
};
// Version
request.Version = new VersionId
{
ServiceId = "ship",
Major = 24, // Check FedEx documentation for current version
Intermediate = 0,
Minor = 0
};
// RequestedShipment
request.RequestedShipment = new RequestedShipment
{
ShipTimestamp = DateTime.Now,
DropoffType = DropoffType.BUSINESS_SERVICE_CENTER,
ServiceType = ServiceType.FEDEX_GROUND,
PackagingType = PackagingType.YOUR_PACKAGING,
TotalInsuredValue = new Money { Amount = 0, Currency = "USD" },
Shipper = new Party
{
AccountNumber = AccountNumber,
Address = new Address
{
StreetLines = new string[] { "123 Main St" },
City = "Anytown",
StateOrProvinceCode = "GA",
PostalCode = "30303",
CountryCode = "US"
},
Contact = new Contact
{
PersonName = "Sender Name",
CompanyName = "Sender Company",
PhoneNumber = "1234567890"
}
},
Recipient = new Party
{
Address = new Address
{
StreetLines = new string[] { "456 Oak Ave" },
City = "Otherville",
StateOrProvinceCode = "GA",
PostalCode = "30301",
CountryCode = "US"
},
Contact = new Contact
{
PersonName = "Recipient Name",
CompanyName = "Recipient Company",
PhoneNumber = "0987654321"
}
},
ShippingChargesPayment = new Payment
{
PaymentType = PaymentType.SENDER,
Payor = new Payor
{
AccountNumber = AccountNumber,
ResponsibleParty = new Party { AccountNumber = AccountNumber }
}
},
LabelSpecification = new LabelSpecification
{
LabelFormatType = LabelFormatType.COMMON2D,
LabelStockType = LabelStockType.PAPER_4X6,
ImageType = LabelImageType.PNG,
ImageTypeSpecified = true,
LabelPrintingOrientation = LabelPrintingOrientationType.TOP_EDGE_OF_TEXT_FIRST,
LabelPrintingOrientationSpecified = true
},
RequestedPackageLineItems = new RequestedPackageLineItem[]
{
new RequestedPackageLineItem
{
SequenceNumber = "1",
Weight = new Weight { Units = WeightUnits.LB, Value = 5.0m },
Dimensions = new Dimensions { Length = "10", Width = "8", Height = "6", Units = "IN" },
CustomerReferences = new CustomerReference[]
{
new CustomerReference { CustomerReferenceType = CustomerReferenceType.CUSTOMER_REFERENCE, Value = "Order123" }
}
}
}
};
try
{
ProcessShipmentReply reply = client.processShipment(request);
if (reply.HighestSeverity == NotificationSeverityType.SUCCESS || reply.HighestSeverity == NotificationSeverityType.NOTE || reply.HighestSeverity == NotificationSeverityType.WARNING)
{
// Extract label image data (Base64 encoded)
CompletedPackageDetail packageDetail = reply.CompletedShipmentDetail.CompletedPackageDetails[0];
string labelBase64 = packageDetail.Label.Parts[0].Image;
// Convert Base64 to byte array
byte[] labelBytes = Convert.FromBase64String(labelBase64);
// You can now save this byte array to a file, stream it to a browser, or print it.
// For example, saving to a file:
// File.WriteAllBytes("fedex_label.png", labelBytes);
return labelBytes;
}
else
{
string errorMessage = "";
foreach (Notification notification in reply.Notifications)
{
errorMessage += $"{notification.Severity}: {notification.Message}\n";
}
throw new Exception($"FedEx API Error: {errorMessage}");
}
}
catch (Exception ex)
{
// Log the exception
Console.WriteLine($"Error creating FedEx label: {ex.Message}");
throw;
}
}
}
public class ShipmentDetails
{
// Placeholder for actual shipment details
// In a real application, this would contain properties for sender, recipient, package info, etc.
}
C# code for constructing a FedEx ProcessShipmentRequest
and calling the API.
wsbeta
.Handling the API Response and Printing Labels
Upon a successful processShipment
call, the ProcessShipmentReply
object will contain the generated label data. The label is typically returned as a Base64 encoded string within the CompletedPackageDetails[0].Label.Parts[0].Image
property. You'll need to decode this string into a byte array, which represents the image or PDF data of the label.
Once you have the label as a byte array, you have several options for printing:
- Save to File: Save the byte array as a
.png
,.jpg
, or.pdf
file to a temporary location on your server. - Stream to Browser: If you want the user to view or print the label directly from their browser, you can stream the byte array with the appropriate
Content-Type
header (e.g.,image/png
orapplication/pdf
). - Direct Printing (Server-Side): For automated printing, you can use .NET's printing capabilities (e.g.,
System.Drawing.Printing
namespace) to send the image directly to a network printer. This often requires the printer to be accessible from the server and careful handling of printer settings.
Remember to handle errors gracefully. The HighestSeverity
property in the ProcessShipmentReply
indicates the outcome of the request. Always check for SUCCESS
, NOTE
, or WARNING
and iterate through the Notifications
collection for detailed messages.
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
public partial class PrintLabel : Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
try
{
// Assume you have a method to get shipment details
ShipmentDetails details = GetShipmentDetailsFromDatabaseOrSession();
FedExLabelGenerator generator = new FedExLabelGenerator();
byte[] labelBytes = generator.CreateAndPrintLabel(details);
// Option 1: Stream to browser for display/download
Response.Clear();
Response.ContentType = "image/png"; // Or "application/pdf" if you requested PDF
Response.AddHeader("Content-Disposition", "inline; filename=fedex_label.png"); // or attachment for download
Response.BinaryWrite(labelBytes);
Response.End();
// Option 2: Save to a temporary file and then redirect or provide a link
// string tempFilePath = Server.MapPath("~/TempLabels/fedex_label_" + Guid.NewGuid().ToString() + ".png");
// File.WriteAllBytes(tempFilePath, labelBytes);
// lblMessage.Text = "Label generated successfully. <a href='" + ResolveUrl(tempFilePath) + "' target='_blank'>View Label</a>";
}
catch (Exception ex)
{
lblMessage.Text = "Error generating label: " + ex.Message;
// Log the exception
}
}
}
private ShipmentDetails GetShipmentDetailsFromDatabaseOrSession()
{
// Implement logic to retrieve actual shipment details
return new ShipmentDetails(); // Placeholder
}
}
Example ASP.NET code for streaming a generated label to the browser.
web.config
sections) to protect these credentials.1. Register for FedEx Developer Account
Visit the FedEx Developer Resource Center and sign up for a developer account to obtain your API credentials (Key, Password, Account Number, Meter Number).
2. Add Service Reference in ASP.NET
In your Visual Studio project, add a Service Reference to the FedEx Ship Service WSDL (e.g., https://wsbeta.fedex.com:443/web-services/ship
). This generates proxy classes for API interaction.
3. Configure API Credentials
Store your FedEx API Key, Password, Account Number, and Meter Number securely in your application's configuration (e.g., web.config
or environment variables).
4. Construct ProcessShipmentRequest
Create an instance of ProcessShipmentRequest
and populate its properties with all necessary shipment details, including sender, recipient, package information, and label specifications.
5. Call processShipment
Method
Instantiate the ShipPortTypeClient
and call its processShipment
method, passing your constructed request object.
6. Process API Response
Check the HighestSeverity
of the ProcessShipmentReply
. If successful, extract the Base64 encoded label image from CompletedPackageDetails
.
7. Decode and Present Label
Convert the Base64 string to a byte array. You can then save it as a file, stream it to the browser, or send it to a printer for physical output.
8. Implement Error Handling
Thoroughly check reply.Notifications
for any errors or warnings and provide meaningful feedback to the user or log the issues.