Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

json-server can we use other key instead of id for post and put request

I have fake api for testing in frontend side.

i have seen that id is required to put or post your data in json-server package, my question is can i use different key instead of id for ex.

{
  id: 1, ---> i want to change this with my custom id
  name: 'Test'
} 
like image 266
Tameshwar Avatar asked Apr 07 '17 12:04

Tameshwar


People also ask

Does a PUT request require an ID?

The PUT method requests that the state of the target resource be created or replaced with the state defined by the representation enclosed in the request message payload. So you can't send a PUT without the ID.

How do I run a json on a different port?

json , you can change the port inside the lite-server module. Go to node_modules/lite-server/lib/config-defaults. js in your project, then add the port in "modules. export" like this.

How can create custom route in json server?

Starting as node module If you start your json-server as a node module instead, you can add custom routing by using the rewrite middleware that comes bundled with json-server.


2 Answers

Let's see CLI options of json-server package: $ json-server -h

...
--id, -i   Set database id property (e.g. _id)   [default: "id"]
...

Let's try to start json-server with new id called 'customId' (for example): json-server --id customId testDb.json

Structure of testDb.json file: $ cat testDb.json

{
  "messages": [
    {
      "customId": 1,
      "description": "somedescription",
      "body": "sometext"
    }
  ]
}

Make a simple POST request via $.ajax function (or via Fiddler/Postman/etc.). Content-type of request should be set to application/json - explanation may be found on this project's github page:

A POST, PUT or PATCH request should include a Content-Type: application/json header to use the JSON in the request body. Otherwise it will result in a 200 OK but without changes being made to the data.

So... Make a request from Browser:

$.ajax({
  type: "POST",
  url: 'http://127.0.0.1:3000/messages/',
  data: {body: 'body', description: 'description'},
  success: resp => console.log(resp),
  dataType: 'json'
});

Go to testDb and see the results. New chunk added. id automatically added with the desired name specified in --id key of console cmd.

{ "body": "body", "description": "description", "customId": 12 }

Voila!

like image 108
dmtrd Avatar answered Dec 30 '22 23:12

dmtrd


I've came up with using custom routes in cases where I need custom id: json-server --watch db.json --routes routes.json

routes.json:

{ "/customIDroute/:cusomID" : "/customIDroute?cusomID=:cusomID" }
like image 34
Eugene Zhukov Avatar answered Dec 31 '22 00:12

Eugene Zhukov