Introduction

This guide explains all important API HTTP status codes (1xx–5xx) and their usage in Azure Functions and APIM.

  • 1xx – Informational
  • 2xx – Success
  • 3xx – Redirection
  • 4xx – Client Errors
  • 5xx – Server Errors
🔹 Clarifications for common doubts:
“Do we send client secret in headers?” – No, only JWT token.
“Where to use status codes?” – Function code returns success/error codes, APIM handles auth errors.

1️⃣ Informational (1xx)

  • 100 Continue – Rare in APIs
  • 101 Switching Protocols – WebSockets / protocol upgrade

2️⃣ Success (2xx)

  • 200 OK – Standard success response for GET/POST
  • 201 Created – New resource created (POST)
  • 202 Accepted – Async processing
  • 204 No Content – Success, no body (DELETE/PATCH)

3️⃣ Redirection (3xx)

  • 301 Moved Permanently – Resource URL changed
  • 302 Found – Temporary redirect (rare in APIs)
  • 304 Not Modified – Caching / CDN

4️⃣ Client Errors (4xx)

  • 400 Bad Request – Invalid JSON / missing parameters
  • 401 Unauthorized – JWT missing or expired
  • 403 Forbidden – Token valid but insufficient scope
  • 404 Not Found – Endpoint URL incorrect
  • 408 Request Timeout – Client timeout
  • 429 Too Many Requests – Rate limit exceeded in APIM

5️⃣ Server Errors (5xx)

  • 500 Internal Server Error – Exception in Azure Function
  • 501 Not Implemented – Feature not supported
  • 502 Bad Gateway – APIM cannot reach Function or Function crashes
  • 503 Service Unavailable – Function offline or cold start
  • 504 Gateway Timeout – Function execution took too long

JSON Response Examples

{
  "status": 401,
  "error": "Unauthorized",
  "message": "JWT token missing or invalid"
}

{
  "status": 403,
  "error": "Forbidden",
  "message": "User does not have required scope"
}

{
  "status": 500,
  "error": "InternalServerError",
  "message": "Unhandled exception in function code"
}
      

Best Practices in Azure Functions (.NET)

  • Return appropriate status codes for each request
  • Use centralized try-catch for error handling
  • APIM handles authentication; Function returns business logic errors
  • Consistent JSON error structure
  • Use Application Insights for logging exceptions

Sample Middleware for Error Handling (.NET Azure Function)

public class ErrorHandlingMiddleware : IFunctionsWorkerMiddleware
{
    public async Task Invoke(FunctionContext context, FunctionExecutionDelegate next)
    {
        try
        {
            await next(context);
        }
        catch(Exception ex)
        {
            var response = context.GetHttpResponseData();
            response.StatusCode = HttpStatusCode.InternalServerError;
            await response.WriteAsJsonAsync(new {
                status = 500,
                error = "InternalServerError",
                message = ex.Message
            });
        }
    }
}