Design API
eL Setiyawan
Hi!
Pakdhe here,
Let’s talk about how to build a proper API.
Disclaimer : What I present here is not a fixed rule,
we can improve it as we need. If there is any
improvement or critique, I'm all ear.
2
“ Remember, we work for our
customers,
You are my customer,
I am your customer.
3
1. No Plain Text Return
Rest API is all about JSON.
{
“error”: “Authorization failed”,
“status”: 401
}
4
2. HTTP Protocol
GET : read record
POST : creating record
PUT : update record
DELETE : delete record
5
… HTTP Protocol
CREATE
POST api/v1/posts
LIST POSTS
GET api/v1/posts
READ SINGLE POST
GET api/v1/posts/{id}
UPDATE SINGLE POST
PUT api/v1/posts/{id}
DELETE SINGLE POST
DELETE api/v1/posts/{id}
6
3. Version Control
We need a version control in our API
URL : api/v1/blogs
URL : api/v2/blogs
7
4. Noun - No Verb!
NO VERB in our API!
DO
Method : POST
URL : api/v1/posts
DONT
Method: POST
URL : api/v1/createPost
8
5. Plural please
To make our API consistent
DO
Method : POST
URL : api/v1/posts
DONT
Method: POST
URL : api/v1/post
9
5. Returning error
Error : required
Detail : optional
{
Status : optional “error”: “Validation failed”,
“detail” : [
“firstName” : “Required”
],
(should status “status”: 400
}
Http code or
simple string? )
10
6. Querystring
q : string max 20
status : string
Method : GET
page : int URL : api/v1/posts
limit : int Example:
order : string api/v1/posts?
q=cob&status=published&page=1&limit=10&order=create
sort : string (asc, desc) dAt&sort=desc
11
More from you ...
12