Mike Holler
Mike Holler

Reputation: 975

Laravel REST API Type Preservation (Ex. how to prevent ints being sent as strings)

This tutorial shows how to make a basic JSON-based REST API using Laravel 4. At the end of the article they show what the REST API outputs:

{
    "error": false,
    "urls": [
        {
            "created_at": "2013-02-01 02:44:34",
            "description": "I feel for him",
            "id": "3",
            "updated_at": "2013-02-02 18:44:18",
            "url": "http://yahoo.com",
            "user_id": "1"
        }
    ]
}

The problem here is that user_id and id are being interpreted and sent as strings, not ints, despite the database type of INTEGER being applied to the columns where these values come from.

Although PHP handles type juggling well, other languages that will be using the REST API we build are picky about types, and it doesn't make sense to force the client to do type conversions on all the data from the API to match how it's represented in the database.

How can I preserve the database's data types on the server, so the client doesn't have to do the work of preserving them.

Ideally, there is a solution where you don't have to iterate through the results on the server and do explicit type conversion there. I'm hoping for something that will preserve values as they are coming out of the database, so CPU cycles aren't wasted on conversion.

Note: we will be using MySQL when we build our API, just in case that changes any of the answers.

Upvotes: 3

Views: 817

Answers (1)

Remluben
Remluben

Reputation: 1673

I read the tutorial on Nettuts+ and I cannot reproduce the output generated by the API. When returning data from the database using models Model::toArray() method the ID field is returned as integer always.

Another way to return data ( assuming, that no additional data is required ) is by simply returning the Model itself. Example:

Route::get('users', function () {
    return User::all(); // returns JSON containing all users
})

Maybe returning numbers as string was an issue while L4 was still in beta status.

Here's another nice tutorial on API design with L4. Maybe http://laracasts.com/video/simple-api-development-with-laravel

Upvotes: 2

Related Questions