Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Phoenix return 200 status code for POST

My Phoenix API returns 200 status code for POST request instead of 201. Phoenix default uses 200 if I am not set the status code.

Here is sample response.

conn |> json(%{created_at: response[:timestamp], notes: response[:notes], data: data})
like image 341
azharmalik3 Avatar asked Aug 15 '16 09:08

azharmalik3


People also ask

What status code should post request return?

Assuming you are writing the API and client:If there IS a new version number: The 201 HTTP status code would fit will. If there is NOT a new version number: The 200 or 204 HTTP status code would fit well.

What is a Phoenix controller?

Phoenix controllers act as intermediary modules. Their functions — called actions — are invoked from the router in response to HTTP requests. The actions, in turn, gather all the necessary data and perform all the necessary steps before invoking the view layer to render a template or returning a JSON response.


1 Answers

You can set the status code manually using Plug.Conn.put_status/2:

conn
|> put_status(:created)
|> json(%{created_at: response[:timestamp], notes: response[:notes], data: data})

Phoenix's phoenix.gen.json task does the same: https://github.com/phoenixframework/phoenix/blob/dd8ce7bd65bd8749e901349d5789bcb94a95521b/priv/templates/phoenix.gen.json/controller.ex#L17.

like image 69
Dogbert Avatar answered Sep 18 '22 10:09

Dogbert