Skip to main content
Redhat Developers  Logo
  • AI

    Get started with AI

    • Red Hat AI
      Accelerate the development and deployment of enterprise AI solutions.
    • AI learning hub
      Explore learning materials and tools, organized by task.
    • AI interactive demos
      Click through scenarios with Red Hat AI, including training LLMs and more.
    • AI/ML learning paths
      Expand your OpenShift AI knowledge using these learning resources.
    • AI quickstarts
      Focused AI use cases designed for fast deployment on Red Hat AI platforms.
    • No-cost AI training
      Foundational Red Hat AI training.

    Featured resources

    • OpenShift AI learning
    • Open source AI for developers
    • AI product application development
    • Open source-powered AI/ML for hybrid cloud
    • AI and Node.js cheat sheet

    Red Hat AI Factory with NVIDIA

    • Red Hat AI Factory with NVIDIA is a co-engineered, enterprise-grade AI solution for building, deploying, and managing AI at scale across hybrid cloud environments.
    • Explore the solution
  • Learn

    Self-guided

    • Documentation
      Find answers, get step-by-step guidance, and learn how to use Red Hat products.
    • Learning paths
      Explore curated walkthroughs for common development tasks.
    • Guided learning
      Receive custom learning paths powered by our AI assistant.
    • See all learning

    Hands-on

    • Developer Sandbox
      Spin up Red Hat's products and technologies without setup or configuration.
    • Interactive labs
      Learn by doing in these hands-on, browser-based experiences.
    • Interactive demos
      Click through product features in these guided tours.

    Browse by topic

    • AI/ML
    • Automation
    • Java
    • Kubernetes
    • Linux
    • See all topics

    Training & certifications

    • Courses and exams
    • Certifications
    • Skills assessments
    • Red Hat Academy
    • Learning subscription
    • Explore training
  • Build

    Get started

    • Red Hat build of Podman Desktop
      A downloadable, local development hub to experiment with our products and builds.
    • Developer Sandbox
      Spin up Red Hat's products and technologies without setup or configuration.

    Download products

    • Access product downloads to start building and testing right away.
    • Red Hat Enterprise Linux
    • Red Hat AI
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products

    Featured

    • Red Hat build of OpenJDK
    • Red Hat JBoss Enterprise Application Platform
    • Red Hat OpenShift Dev Spaces
    • Red Hat Developer Toolset

    References

    • E-books
    • Documentation
    • Cheat sheets
    • Architecture center
  • Community

    Get involved

    • Events
    • Live AI events
    • Red Hat Summit
    • Red Hat Accelerators
    • Community discussions

    Follow along

    • Articles & blogs
    • Developer newsletter
    • Videos
    • Github

    Get help

    • Customer service
    • Customer support
    • Regional contacts
    • Find a partner

    Join the Red Hat Developer program

    • Download Red Hat products and project builds, access support documentation, learning content, and more.
    • Explore the benefits

How to use third-party APIs in Operator SDK projects

February 4, 2020
Camila Macedo
Related topics:
DevOpsKubernetesOperators
Related products:
Red Hat OpenShift

    The Operator Framework is an open source toolkit for managing Kubernetes-native applications. This framework and its features provide the ability to develop tools that simplify complexities, such as installing, configuring, managing, and packaging applications on Kubernetes and Red Hat OpenShift. In this article, we show how to use third-party APIs in Operator-SDK projects.

    In projects built with Operator-SDK, only the Kubernetes API schemas are added by default. However, you might need to create, read, update, or delete a resource that is from another API—even one that you created yourself via other Operator projects.

    Let's check out an example scenario: How to create a Route resource from the OpenShift API for an Operator-SDK project.

    Step 1: Get the API module

    In your project's directory, run the following command via the command line to get the OpenShift API module:

    $ go get -u github.com/openshift/api

    Step 2: Use the Discovery API to see if the new API is present

    The best approach at this point is to make sure that the resource is available in the cluster because we are using a third-party API. You can learn how to check that the resource is available by reading Why not couple an Operator's logic to a specific Kubernetes platform?

    Note: If what you are building must run on a specific Kubernetes platform (for example, OpenShift) be aware that users might still try to use your project with other Kubernetes platform vendors. For example, they might try to check your Operator with Minikube. In this scenario, your project might fail if you do not adequately implement it because the OpenShift APIs will not be present. Best practices recommend that you create Operator projects that are supportable for both scenarios. In this example, we could use the v1.Route if it is available in the cluster, or we could create an Ingress.

    Step 3: Register the API with the scheme

    In the main.go file, add the schema before the line Setup all Controllers:

        ...
        // Adding the routev1
    	if err := routev1.AddToScheme(mgr.GetScheme()); err != nil {
    		log.Error(err, "")
    		os.Exit(1)
    	}
        
        // Setup all Controllers
    	if err := controller.AddToManager(mgr); err != nil {
    		log.Error(err, "")
    		os.Exit(1)
    	}
        ...
    

    Note that you need to import the module as well:

    import (
    	...
    	routev1 "github.com/openshift/api/route/v1"
    	...
    )

    Step 4: Use the API in the controllers

    Now, we can create the Route resource in the controller.go file's Reconcile function. Continuing with our example:

            ...
            route := &routev1.Route{}
            err = r.client.Get(context.TODO(), types.NamespacedName{Name: memcached.Name, Namespace: memcached.Namespace}, route)
            if err != nil && errors.IsNotFound(err) {
    	    // Define a new Rooute object
    	    route = r.routeForMemcached(memcached)
    	    reqLogger.Info("Creating a new Route.", "Route.Namespace", route.Namespace, "Route.Name", route.Name)
                err = r.client.Create(context.TODO(), route)
                if err != nil {
    		    reqLogger.Error(err, "Failed to create new Route.", "Route.Namespace", route.Namespace, "Route.Name", route.Name)
    		    return reconcile.Result{}, err			
                }
    	} else if err != nil {
    	    reqLogger.Error(err, "Failed to get Route.")
    	    return reconcile.Result{}, err
    	}
            ...

    Create the Route itself:

    // routeForMemcached returns the route resource
    func (r *ReconcileMemcached) routeForMemcached(m *cachev1alpha1.Memcached) *routev1.Route {
    
    	ls := labelsForMemcached(m.Name)
    	route := &routev1.Route{
    		ObjectMeta: metav1.ObjectMeta{
    			Name:      m.Name,
    			Namespace: m.Namespace,
    			Labels:    ls,
    		},
    		Spec: routev1.RouteSpec{
    			To: routev1.RouteTargetReference{
    				Kind: "Service",
    				Name: m.Name,
    			},
    			Port: &routev1.RoutePort{
    				TargetPort: intstr.FromString(m.Name),
    			},
    			TLS: &routev1.TLSConfig{
    				Termination: routev1.TLSTerminationEdge,
    			},
    		},
    	}
    
    	// Set MobileSecurityService mss as the owner and controller
    	controllerutil.SetControllerReference(m, route, r.scheme)
    	return route
    }

    Also, it is possible to re-trigger the reconcile if any change occurs on this resource:

    	err = c.Watch(&source.Kind{Type: &routev1.Route{}}, &handler.EnqueueRequestForOwner{
    		IsController: true,
    		OwnerType:    &cachev1alpha1.Memcached{},
    	})
    	if err != nil {
    		return err
    	}
    

    Step 5: Use the API to implement unit tests

    You need to develop tests to check your implementation in order to add the third-party schema into the manager used by the fake client provided by the Operator-SDK test framework. See the following example:

    func buildReconcileWithFakeClient(objs []runtime.Object, t *testing.T) *ReconcileMemcached {
    	s := scheme.Scheme
    
    	// Add route Openshift scheme
    	if err := routev1.AddToScheme(s); err != nil {
    		t.Fatalf("Unable to add route scheme: (%v)", err)
    	}
    
    	s.AddKnownTypes(&v1alpha1.Memcached{}, &v1alpha1.AppService{})
    
    	// create a fake client to mock API calls with the mock objects
    	cl := fake.NewFakeClient(objs...)
    
    	// create a ReconcileMemcached object with the scheme and fake client
    	return &ReconcileMemcached{client: cl, scheme: s}
    }

    Use the above function to implement the tests as follows:

    func TestReconcileMemcached(t *testing.T) {
    	type fields struct {
    		scheme *runtime.Scheme
    	}
    	type args struct {
    		instance *1alpha1.Memcached
    		kind     string
    	}
    	tests := []struct {
    		name      string
    		fields    fields
    		args      args
    		want      reconcile.Result
    		wantErr   bool
    		wantPanic bool
    	}{
    		// TODO: Tests
    	}
    	for _, tt := range tests {
    		t.Run(tt.name, func(t *testing.T) {
    
    			objs := []runtime.Object{tt.args.instance}
    			r := buildReconcileWithFakeClient(objs, t)
    
                if (err != nil) != tt.wantErr {
    				t.Errorf("TestReconcileMemcached error = %v, wantErr %v", err, tt.wantErr)
    				return
    			}
    		})
    	}
    }

    Now, you know how to use third-party APIs in your Operator projects. And not just that, you also have a good idea about the code's re-use capabilities as well.

    I'd like to thank @Joe Lanford, who also collaborated with feedback and input for this article.

    Last updated: October 8, 2024

    Recent Posts

    • Tekton joins the CNCF as an incubating project

    • Federated identity across the hybrid cloud using zero trust workload identity manager

    • Confidential virtual machine storage attack scenarios

    • Introducing virtualization platform autopilot

    • Integrate zero trust workload identity manager with Red Hat OpenShift GitOps

    Red Hat Developers logo LinkedIn YouTube Twitter Facebook

    Platforms

    • Red Hat AI
    • Red Hat Enterprise Linux
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products

    Build

    • Developer Sandbox
    • Developer tools
    • Interactive tutorials
    • API catalog

    Quicklinks

    • Learning resources
    • E-books
    • Cheat sheets
    • Blog
    • Events
    • Newsletter

    Communicate

    • About us
    • Contact sales
    • Find a partner
    • Report a website issue
    • Site status dashboard
    • Report a security problem

    RED HAT DEVELOPER

    Build here. Go anywhere.

    We serve the builders. The problem solvers who create careers with code.

    Join us if you’re a developer, software engineer, web designer, front-end designer, UX designer, computer scientist, architect, tester, product manager, project manager or team lead.

    Sign me up

    Red Hat legal and privacy links

    • About Red Hat
    • Jobs
    • Events
    • Locations
    • Contact Red Hat
    • Red Hat Blog
    • Inclusion at Red Hat
    • Cool Stuff Store
    • Red Hat Summit
    © 2026 Red Hat

    Red Hat legal and privacy links

    • Privacy statement
    • Terms of use
    • All policies and guidelines
    • Digital accessibility

    Chat Support

    Please log in with your Red Hat account to access chat support.