Evorlor
Evorlor

Reputation: 7553

What is the correct status code for a semi-ok response?

I have a client that is asking the server for n elements. The server is asking ChatGPT for n elements, but sometimes ChatGPT returns n-1 or n+1 elements.

Client Code

const count = 3;
var elements = Server.GetElements(count);
for(int i = 0; i < elements.Count; i++)
{
    DoStuff(elements[i]); // Index out of bounds
}

Server Code

var count = ClientRequest.GetCount(); // Client requests 3 elements
List elements = ChatGPT.GetElements(count); // Server returns 4 elements
return elements;

This is going to happen. Ideally, I will fix the server so it always returns the correct number of elements. But ChatGPT is sometimes unpredictable, and I can't invest all my time working out these edge cases.

When the server returns the incorrect number of elements, what should the HTTP Status Code be? Should it still return a 200, or something else?

My normal responses contain a data field, and a meta field with the status code. If this happens, should there be an additional error field? Or would that information belong in the meta field?

Note: I am not asking about paging.

Upvotes: -1

Views: 47

Answers (1)

Prakash P
Prakash P

Reputation: 4058

For partial data, I use both HTTP status code: 200 OK or 206 Partial Content based on the situations.

  • 200 OK: When the server successfully processes the request, even if the data is incomplete, you can use 200. You may consider metadata in the response to indicate that the content is partial:

    {
        "elements": [/* partial list */],
        "isPartial": true,
        "message": "This is a incomplete list."
    }
    
  • 206 Partial Content: This is used to indicate partial responses. Can be used with paginated data, byte streams etc.. . For example:

    HTTP/1.1 206 Partial Content
    Content-Range: items 0-49/100
    
    {
        "elements": [/* partial list */],
        "total": 100,
        "returned": 50,
        "message": "Partial response."
    }
    

Which Should You Use?

  • Use 200 OK if partial data is expected and the client doesn’t need to distinguish it from full data. You can communicate partiality in the response body or headers.
  • Use 206 Partial Content when it’s important to highlight the response is intentionally incomplete (e.g., a range or pagination).

It comes to the personal choice to use 200 or 206.

Upvotes: 1

Related Questions