Return JSON response with custom status code
See original GitHub issueHello,
I’m building a JSON api using spirit. I’ve started by adding catch-all route to return 404 response.
route.get("*", {
status: 404,
headers: {
'Content-Type': 'application/json'
}
body: JSON.stringify({
message: 'Not Found',
})
})
While it works, it’s a little bit verbose.
Is there a shorter way to do that, maybe something like:
route.get("*", response.json(404, { message: "Not Found" }))
Thanks, Ran.
Issue Analytics
- State:
- Created 7 years ago
- Comments:5 (2 by maintainers)
Top Results From Across the Web
Return JSON with error status code MVC - Stack Overflow
A simple way to send a error to Json is control Http Status Code of response object and set a custom error message....
Read more >Return JSON Result with Custom Status Code in ASP.NET Core
NET Core responses and learn how to return a JSON result with custom status code through the help of formatters or directly from...
Read more >HTTP status and error codes for JSON | Cloud Storage
HTTP status and error codes for JSON · 302—Found · 303—See Other · 304—Not Modified · 307—Temporary Redirect · 308—Resume Incomplete · 400—Bad...
Read more >how to return JSON and a response status like 201 #1520
I have a POST route that I want to return JSON and a response status of ... you could also use status::Custom to...
Read more >Return a Response Directly - FastAPI
But you can return a JSONResponse directly from your path operations. It might be useful, for example, to return custom headers or cookies....
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
will produce a response with status code 404, and json content type header set, and a json body.
Also as per your suggestion @ranyefet I updated the
response
helper function to be:spirit v0.4.0 & spirit-router v0.4.0
Closing, if there’s an issue or another suggestion feel free to let me know ✌️
Hey @ranyefet ,
You can do
route.get("*", ...)
to catch GET only, or there is alsoroute.not_found(...)
which will 404 on every request regardless of method. (Ex:route.not_found("Page is not found")
ornotFound
is camelCase alias to it.You mentioned the explicit way, there’s also @dodekeract suggestion.
You also mentioned “response.json”, there is a helper function similar to that:
Also this should work (but it doesn’t, so will need to fix):
Which would do what you want. Will upload fix by tonight (spirit-router@0.4.0).