Hacker News new | past | comments | ask | show | jobs | submit login
Ask HN: REST API response – Should you envelope or not?
5 points by googlycooly on Jan 26, 2021 | hide | past | favorite | 2 comments
Can anyone who has years of experience in building REST APIs explain which option is better? To envelop or not?

If we envelop, what should be the key? Should it be common for all responses like "data":[] or specific to resources like "users":[]




I always do. Been working with rest api’s for 10 years. Mostly because front enders and other api consumers I work with like the standard response and because I can give details about the backend. I put everything into a response key but data would work.

I put in a few standard fields. Time which is utc to catch caching issues. Messages for useful messages such as DB down fell over to cache or some such. Success which is used to indicate if everything worked. Note I use http codes for failures but say something fell over to a backup this would be set to false. I also have timing which contains the time for backend calls to respond or other such processing times. This is helpful when someone says a call is slow, just view the response and you get an idea where the issue might be. Has saved me a few times when integrating with 3rd parties and allows for finger pointing that’s not at me.

An example below.

    {
        "success": true,
        "messages": [],
        "time": "2021-01-26T07:49:28.635248481Z",
        "timing": [
            {
                "timeMillis": 0,
                "source": "HealthCheck"
            }
        ],
        "response": {
            "memUsage": "memoryusage::Alloc = 7025 MB::TotalAlloc = 82490487 MB::Sys = 17503 MB::tNumGC = 31354"
        }
    }


Envelope. It allows you to add metadata if you want (e.g. request ID, cache date, response time, paging info, or anything else that's relevant).




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: