Returning Complex Objects from an API in VBPI

Jul 9, 2024

Returning Complex Objects from an API in VBPI

Introduction

  • Presenter: Venkat
  • Series: VBPI Tutorials, Part 7
  • Topic: How to return complex objects, such as classes or lists of classes, from an API

Previous Tutorial Recap

  • Previously covered how to return a simple string from an action method or endpoint.

Objective of This Tutorial

  • Demonstrate how to return complex objects or lists of classes from an API.
  • Focus on updating the Student controller to return a list of student objects.

Steps Covered

Modifying the Student Controller

  • Remove Unnecessary Controllers: Removed the ValuesController.
  • Update Action Method: Modified the GetStudents action method to return IEnumerable<Student>.

Creating the Student Model

  • Add Models Folder: Created a new folder named Models.
  • Add Student Class: Inside the Models folder, added a new class named Student.
    • Fields in Student class:
      • StudentID
      • StudentName
      • EmailAddress
      • StudentAddress

Preparing List of Students

  • Import Namespace: Ensure the relevant namespace is imported.
  • Create Student Objects:
    • Created two instances of Student with example data:
      • StudentID = 1, StudentName = "Student 1", Email = "email1@gmail.com", Address = "Hyderabad, India"
      • StudentID = 2, StudentName = "Student 2", Email = "email2@gmail.com", Address = "Bangalore, India"
  • Action Method:
    • The GetStudents action method returns a list of students.

Execution

  • Use the "Try it out" feature to execute the method.
  • Confirmed that two different student details are returned as expected:
    • Student 1: email1@gmail.com, Hyderabad, India
    • Student 2: email2@gmail.com, Bangalore, India

Refactoring for Better Practice

  • Issue: Hardcoding student data directly in the action method is not elegant.
  • Solution: Move the data to a repository (static repository for this example).
  • Benefit: Improves code maintainability and readability.

Conclusion

  • Appreciation for watching.
  • Encouragement to like, share, and subscribe for more tutorials.