Create Barcodes in Swift / iOS

This Swift sample code shows how to create barcodes with the McAPI Barcode REST API service. The sample uses Swift 5.

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

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

Create a Barcode using Swift with NSMutableURLRequest

Shown is the creation of a Code 128 (code type: 7) with Swift 5. All parameters relevant for the actual barcode creation are in the parameters-array which is JSON encoded and then added as a payload to the request.

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:

// Listing: Create barcodes in Swift 5
import Foundation
import UIKit

struct Result : Decodable{
  let service: String
  let version: String
  let format: String
  let code: String

let headers = [
  "content-type": "application/json",
  "x-rapidapi-key": "YOUR_API_KEY",
  "x-rapidapi-host": ""

let parameters = [
  "data": "123456",
  "type": 7,
  "moduleWidth": 0.5,
  "moduleHeight": 20,
  "format": "pdf",
] as [String : Any]

let postData = try parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  else {
    let httpResponse = response as? HTTPURLResponse
    if httpResponse?.statusCode == 200{
      if let data = data{
      // handle 400 errors here, see documentation for possible error conditions


After performing the request, the response will be delivered as JSON in data:

  "service":"McAPI Barcode Generator,",
  "code":"data:application/pdf;base64,JVBE ... Cg=="

Sample barcode with Swift

The returned code from the Swift snippet:

Image of Sample Barcode Swift

This is just an introductory example. We provide more Swift sample code and an iOS Playground for barcode creation here.