简体   繁体   中英

REST API design, which pattern to use

I have a requirement for a faster REST API for a mobile application. I have designed two type of responses for APIs. Which is the better approach? **

  • Option 1

**

{    
  data :[ 
          {name:"abc",email:"abc@abc.abc",id:12,age:24},
          {name:"abc",email:"abc@abc.abc",id:13,age:24}
        ]
}

**

  • Option 2

**

{
     fields:['name','email','id','age'],
     values:[
                ['abc','abc@abc.abc',12,45],
                ['abc','abc@abc.abc',12,45]
            ]
}

Obviously the second one generates less response length (consider the case of 1000 records in single response) and faster output as, the keys are not repeated.

Can somebody suggest the best practise?

Option 1 is a general standard across most APIs. It makes parsing and mapping the JSON response to model classes much easier as most libraries (GSON, Jackson etc.) are designed with #1 in mind. I'd highly recommend you choose #1. ;)

Also, things can get complicated with #2 if you introduce nested objects down the road.

You can read more about the JSON spec here .

I prefer the first one. why? because there is one constant fact in software development and that is CHANGE . If the system dose not change it will die soon, so in order to prepare yourself for future changes you should use #1. you can add fields and also remove fields and tell the clients for example check for existence of fields before using it. You can also make yourself decouple from fields ordering. You also make for future developers work with your system easier. That is why every system uses #1 and in order to reduce the size you can use Gzip.

Good Luck.

Option 1 should be developers' choice due to it's readability and maintainability. I agree with arsent about the nested objects. For about the speed, JSON has been supporting different languages and can be compressed to make the file smaller as it is composed of texts and can get up to 90% compression using gzip whenerver possible.

One indeed. Uses the object notation as it is meant to be used. Much more readable than 2, much easier to extend, parse and operate with.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM