Hii Mudasir,
I encountered the same issue with setting the response status code in APIs using type='json'. To solve it, I switched my controller to type='http', which worked perfectly.
While "Cybrosys Techno Solutions Pvt.Ltd" offers a reasonable solution, it only sets the status code inside the result, not for the entire API response. Other approaches also involve some additional customizations.
The solution is simple: you can set the status code and return any response you need by using type='http' and returning request.make_response.
Take a look at the example code below:
@http.route('/api/custom_endpoint', type='http', auth='public', methods=['GET'])
def custom_endpoint(self):
"""
A simple example of an Odoo GET API endpoint that returns a custom status code.
:return: JSON response with status code.
"""
# Example response data
data = {
'message': 'Hello, this is a custom response!',
}
# Convert the response data to JSON format
data = json.dumps(data)
# Create an HTTP response with status code 200 (OK)
response = request.make_response(
data,
headers=[
('Content-Type', 'application/json'),
('Cache-Control', 'no-cache'),
],
status=200 # You can change this to any status code you need
)
return response