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})
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With