McAPI - Barcode API C#

C# sample code to create barcodes with the McAPI Barcode REST API service. We provide a simple VS console app (VisualStudio 2019 or newer) that you can use for testing, download. The sample uses C# with .NET 5 but older .NET runtimes should work too. To parse the returned JSON, the sample project uses Newtonsoft Json which can be installed via the NuGet package manager.

Requirements: A free RapidAPI account. Replace YOUR_API_KEY with your own api key.

All samples below work with the free tier of the API, see RapidAPI McAPI Barcode Listing for available plans.

See the overview page for a reference that lists all available parameters and error codes.

Create a Barcode using C# with HttpClient

Shown is the creation of a Code 128 (code type: 7) with C#. All parameters relevant for the actual barcode creation are in the payload-string which is added as content to the request. The payload-string is formatted as a C# verbatim string for better readability.

The data to encode in the barcode is "123456". The module width is set to 0.5mm, the height is set to 20mm, the size of the human readable text under the barcode is set to 10 points. The code is returned as a base64 encoded PDF.

The source code:

// C#
  
using Newtonsoft.Json;
using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace BarcodeAPI
{
    public class Result
    {
        public string service { get; set; }
        public string version { get; set; }
        public string format { get; set; }
        public string code { get; set; }
    }

    class Program
    {
        static async Task Main(string[] args)
        {

            string payload = @"
            {
                ""data"": ""123456"",
                ""type"": 7,
                ""moduleWidth"": 0.5,
                ""moduleHeight"": 20,
                ""hrText"": 10
                ""format"": ""pdf""
            }";

            using (var client = new HttpClient())
            {
                var request = new HttpRequestMessage
                {
                    Method = HttpMethod.Post,
                    RequestUri = new Uri("https://mcapi-barcode.p.rapidapi.com/"),
                    Headers =
                    {
                        { "x-rapidapi-key", "YOUR_API_KEY" },
                        { "x-rapidapi-host", "mcapi-barcode.p.rapidapi.com" },
                    },
                    Content = new StringContent(payload)
                    {
                        Headers =
                        {
                            ContentType = new MediaTypeHeaderValue("application/json")
                        }
                    }
                };

                using (var response = await client.SendAsync(request))
                {
                    response.EnsureSuccessStatusCode();
                    var body = await response.Content.ReadAsStringAsync();
                    ...
                }
            }
        }
    }
}

After performing the request, the response will be delivered as JSON in body, see further below for a snippet on how to parse the data:

{
  "service":"McAPI Barcode Generator, https://mcapi.io",
  "version":"V1",
  "format":"pdf",
  "code":"data:application/pdf;base64,JVBE ... Cg=="
}

McAPI Barcode API - Sample barcode with C#

The returned code from the C# snippet:

Image of McAPI Barcode API Sample Barcode C#

Creating retail barcodes EAN, ISBN, UPC with C#

The introductory sample above created a Code 128 barcode. Code 128 has many applications, mostly in warehousing and logistics. In the following C# snippet we show how to create EAN and UPC barcodes which are used in retail.

Let's create an EAN 13 code. First step is to set the code type. The reference section lists all available code types; for EAN 13, we have to set the type-parameter to "1". With Code 128, we set the size of the code by specifing values for moduleWidth and moduleHeight. Retail codes are standardized, with the standard specifying the permitted sizes (so called SC sizes). With the Barcode API, the size of retail barcodes is determined through the size-parameter, with "2" being the 100% size. Here's the payload block for creating an EAN 13 encoding "401234567890", again returning a PDF:

// C#

...

string payload = @"
{
    ""data"": ""401234567890"",
    ""type"": 1,
    ""size"": 2,
    ""format"": ""pdf""
}";

...

Here's the resulting EAN 13:

Image of McAPI Barcode API EAN 13 Barcode C#

As an aside, the reference section also specifies the expected data for each barcode symbology. EAN 13 encodes twelve digits plus check digit (hence the name). As such you'll have to specify twelve or thirteen digits, less than twelve or more than thirteen will result in an error, likewise if the submitted data contains letters. As a convenience, the API will always recalculate the check digit for retail codes to make sure that a valid symbol is created; in this example the EAN 13 check digit is "1" which will be appended automatically to the provided data.

The greater-character (">") to the right of the code is the so called light margin indicator. This indicator tells the graphics designer not to put other graphical elements too close to the code. The indicator can be switched off by setting the lmi-parameter to "false".

Truncated EAN 13 with reduced height (C#)

EAN barcodes can get quite large, with smaller packages or cartons the code might not fit into the available space. Per the standard, it's permitted to reduce the height of the code to some degree. The Barcode API supports a special truncate-parameter for retail codes. The parameter is percentage based, e.g. "50" will create a code with half height.

Sample payload block:

// C#

...

string payload = @"
{
    ""data"": ""401234567890"",
    ""type"": 1,
    ""size"": 2,
    ""truncate"": 50,
    ""format"": ""pdf""
}";

...

Here's the resulting EAN 13 with half height:

Image of McAPI Barcode API EAN 13 Truncated Barcode C#

EAN 13 with additional text (C#)

A very useful feature of the Barcode API is the support for additional text that can be put above and below the barcode. This can be used for article descritions, pricing, weight, best before dates etc.

The parameters over, under and suppSize control any additional text. The following payload block will put the text "Paperclips" above the code, the text "$2.99" below the code and set the font size for the additional text to 8pt.:

// C#

...

string payload = @"
{
    ""data"": ""401234567890"",
    ""type"": 1,
    ""size"": 2,
    ""truncate"": 50,
    ""over"": ""Paperclips"",
    ""under"": ""$2.99"",
    ""suppSize": 8,
    ""format"": ""pdf""
}";

...

The resulting EAN 13 with additional text:

Image of McAPI Barcode API EAN 13 Price Best before Barcode C#

Note: Additional text must be from the ASCII character set, Unicode is not supported. Max. 30 characters allowed.

Creating an EAN barcode without text (C#)

Sometimes you will only want the actual barcode without any text at all; that's possible too: Simply specify the hrText-parameter as "false", like so:

// C#
  
...

string payload = @"
{
    ""data"": ""401234567890"",
    ""type"": 1,
    ""size"": 2,
    ""truncate"": 50,
    ""hrText"": ""false"",
    ""format"": ""pdf""
}";

...

The resulting EAN 13 without any text:

Image of McAPI Barcode API EAN 13 No text Barcode C#

Creating 2D matrix barcodes with C#

The Barcode API supports the most common 2D barcode symbologies: Datamatrix, Datamatrix GS1, PDF417, QR and Aztec. Creating those codes in C# is no different from creating standard, linear barcodes; the only aspect to consider is using the moduleWidth-parameter to control the size of the code. With the exception of PDF417, dots are square, i.e. moduleWidth equals moduleHeight. With PDF417, the dots are created with a 3:1 ratio, i.e. moduleHeight equals 3 * moduleWidth.

The following payload block will create a Datamatrix code (type = "16") with a dot size of 1x1mm²:

// C#

...

string payload = @"
{
    ""data"": ""1234567890"",
    ""type"": 16,
    ""moduleWidth"": 1,
    ""format"": ""pdf""
}";

...

The resulting Datamatrix code:

Image of McAPI Barcode API Datamatrix 2D Barcode C#

2D barcodes are always created without text as the encoded data is typically too much to be displayed. Use the over and under parameters to put small amounts of text (max. 30 chars) next to the code.

Create QR codes with C#

The Barcode API supports the creation of QR codes that can contain plain text, URLs, email addresses, phone numbers and SMS numbers.

Note: Our QR implementation is fully Unicode-compatible but expects data with utf-8 encoding. Since C# strings use utf-16, any Unicode content has to be converted to utf-8; the .NET Encoding namespace provides a number of useful conversion methods.

Specify content as follows:

  • Plain text (max. 2,000 chars): "123456abcdefÄÖÜ日本語"
  • URL: Specify data param like so: "https://example.com"
  • Email: Specify data param like so: "mailto:info@example.com"
  • Phone no: Specify data param like so: "tel:+18005551234"
  • SMS: Specify data param like so: "smsto:44044"

Sample payload block to create a QR code with the URL "https://mcapi.io":

// C#

...

string payload = @"
{
    ""data"": ""https://mcapi.io"",
    ""type"": 19,
    ""moduleWidth"": 1,
    ""format"": ""pdf""
}";

...

The resulting QR code:

Image of McAPI Barcode API QR URL Barcode C#

The header-parameter - creating PNG image files from barcodes (C#)

With all supported formats, the barcode is returned as a base64 encoded string. Per default, this string is preceded by a header that describes the media type (or MIME) of the string.

Sample payload block for a QR code, to be returned as a PNG:

// C#
  
...

string payload = @"
{
    ""data"": ""https://mcapi.io"",
    ""type"": 19,
    ""moduleWidth"": 1,
    ""format"": ""png""
}";

...

The result will look like this, note the image/png section:

{
  "service":"McAPI Barcode Generator, https://mcapi.io",
  "version":"V1",
  "format":"png",
  "code":"data:image/png;base64,iVBOR ... QmCC"
}

After parsing the result with a JSON parser you can directly set the "code"-string as the src property of an img tag. This is particularly useful if you want to load barcodes into a web view, like so:

// C#

...

using (var client = new HttpClient())
{
    ...

    using (var response = await client.SendAsync(request))
    {
        response.EnsureSuccessStatusCode();
        var body = await response.Content.ReadAsStringAsync();
        var barcode = JsonConvert.DeserializeObject(body).code;
        var img = "<img src=\"" + barcode + "\"/>";
        webView.NavigateToString(img);
    }
}

...

The MIME header will make sure that the image data is interpreted correctly by the browser. However, if you want to create an actual PNG image file from the data the header has to be left out. To create a code without the header, set the header-parameter to "false", like so:

// C#
  
...

string payload = @"
{
    ""data"": ""https://mcapi.io"",
    ""type"": 19,
    ""moduleWidth"": 1,
    ""header"": ""false"",
    ""format"": ""png""
}";

...

The returned code without header:

{
  "service":"McAPI Barcode Generator, https://mcapi.io",
  "version":"V1",
  "format":"png",
  "code":"iVBOR ... QmCC"
}

Now, all we have to do is decode the base64 string and then write the PNG data to a file. Shown as a complete example (this is the contents of the provided VS project, see link in the introduction):

// C#

using Newtonsoft.Json;
using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace BarcodeAPI
{
    public class Result
    {
        public string service { get; set; }
        public string version { get; set; }
        public string format { get; set; }
        public string code { get; set; }
    }

    class Program
    {
        static async Task Main(string[] args)
        {

            string payload = @"
            {
                ""data"": ""https://mcapi.io"",
                ""type"": 19,
                ""moduleWidth"": 1,
                ""header"": ""false"",
                ""format"": ""png""
            }";

            using (var client = new HttpClient())
            {
                var request = new HttpRequestMessage
                {
                    Method = HttpMethod.Post,
                    RequestUri = new Uri("https://mcapi-barcode.p.rapidapi.com/"),
                    Headers =
                    {
                        { "x-rapidapi-key", "YOUR_API_KEY" },
                        { "x-rapidapi-host", "mcapi-barcode.p.rapidapi.com" },
                    },
                    Content = new StringContent(payload)
                    {
                        Headers =
                        {
                            ContentType = new MediaTypeHeaderValue("application/json")
                        }
                    }
                };

                using (var response = await client.SendAsync(request))
                {
                    response.EnsureSuccessStatusCode();
                    var body = await response.Content.ReadAsStringAsync();
                    var barcode = JsonConvert.DeserializeObject<Result>(body).code;
                    var png = Convert.FromBase64String(barcode);
                    var path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "barcode.png");
                    File.WriteAllBytes(path, png);
                }
            }
        }
    }
}

Back to McAPI Barcode API main page.