Create Barcodes in Ruby

A quick way to create barcodes in Ruby is Barby, a free and easy to use GEM which can produce many common barcode symbologies. However, Barby won't solve all barcode problems:

Barby vs Barcode API for Ruby

A more comprehensive alternative to Barby is the McAPI Barcode API which addresses most of Barby's shortcomings: More barcode symbologies, widely configurable human readable text for the codes plus additional text (for pricing, article names etc.) and no dependencies except for the built-in uri, net and openssl modules.

Using the McAPI Barcode API with Ruby

This Ruby sample code shows how to create a barcode with the McAPI Barcode REST API service. The sample uses Ruby 2 but the code will also work with Ruby 3.

Requirements: A RapidAPI account. Replace YOUR_API_KEY in the code snippets below with your own api key.

The sample works 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.

Shown is the creation of a Code 128 (code type: 7) with Ruby. All relevant parameters are in the body of the request. The barcode will encode the text "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 will be created and returned as a base64 encoded PDF.

The source code:

# Listing: Create barcodes in Ruby
  
require 'uri'
require 'net/http'
require 'openssl'

url = URI("https://mcapi-barcode.p.rapidapi.com/")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE

request = Net::HTTP::Post.new(url)
request["content-type"] = 'application/json'
request["x-rapidapi-key"] = 'YOUR_API_KEY'
request["x-rapidapi-host"] = 'mcapi-barcode.p.rapidapi.com'
request.body = "{
    \"data\": \"123456\",
    \"type\": 7,
    \"moduleWidth\": 0.5,
    \"moduleHeight\": 20,
    \"hrSize\": 10,
    \"format\": \"pdf\",
}"

response = http.request(request)

The data will be delivered as JSON in response.read_body e.g.:

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

Sample barcode with Ruby

The returned code from the Ruby request:

Image of Sample Barcode Ruby

This is just an introductory example. We provide more barcode sample code in Ruby and other languages here.