New-PSUApiResponse - data type

Product: PowerShell Universal
Version: 3.6.3

I have created an API for provisioning new databases, which is working just fine.
The client executes something like this:

$Body = [PSCustomObject]@{
    DatabaseName = "DB12"
    Type         = "Production"
} | ConvertTo-Json 
Invoke-RestMethod http://192.168.2.26:5000/api/test/sql/newdatabase -Method POST -Body $Body -AllowUnencryptedAuthentication -ErrorAction Stop    

The API looks like this:

$SQLBody = $body | ConvertFrom-Json
switch ($SQLBody.type) {
    "Production" {
        $SQLInstance = "dk1sql01"
        $RecoveryModel = "Full"
    }
    "Developer" {
        $SQLInstance = "dk1sql02"
        $RecoveryModel = "Simple"
    }
}

try {
    $ExisitingDatabaseCheck = Get-DbaDatabase -SqlInstance $SQLInstance -Database $SQLBody.DatabaseName
    if ($ExisitingDatabaseCheck) {
        New-PSUApiResponse -Body "A database with that name already exist - please select a new one!" -StatusCode 404
    }
}
catch {
    New-PSUApiResponse -Body "Failed to check if the database already exists - $($_.Exception.Message)" -StatusCode 404
}


try {
    $TempVar = New-DbaDatabase -SqlInstance $SQLInstance -Name $SQLBody.DatabaseName -RecoveryModel $RecoveryModel -ErrorAction stop 
    $returnbody = [PSCustomObject]@{
        DatabaseName = $SQLBody.DatabaseName
        SQLInstance  = $SQLInstance
    }
    New-PSUApiResponse -Body $returnbody -StatusCode 200
}
catch {
    New-PSUApiResponse -Body "$($_.Exception.Message)" -StatusCode 404
    throw "$($_.Exception.Message)"
}

My question is - i need to return the $returnbody to the client, since i need to return what SQL server was selected for the database (in the future, more data will be returned).

But the response im getting from Invoke-RestMethod seems to be a string… How do i return this as a real object with properties, that i can use?

Technically you could probably just cast the string object to a PsCustomObject.

However if you want Invoke-RestMethod to automatically map it to an object you’ll want to return JSON. If you explicitly use New-PSUApiResponse then you’ll have to convert your object to JSON using the ConvertTo-Json cmdlet

$returnbody = [PSCustomObject]@{
        DatabaseName = $SQLBody.DatabaseName
        SQLInstance  = $SQLInstance
    } | ConvertTo-Json

Ive tried everything - except for the one solution, that made sense :slight_smile:
It works - thanks a lot!