Skip to main content

Command Palette

Search for a command to run...

Coding Exercise: Mock HTTP Status Code

Updated
1 min read
Coding Exercise: Mock HTTP Status Code
H

I am a developer from Malaysia. I work with PHP most of the time, recently I fell in love with Go. When I am not working, I will be ballroom dancing :-)

Sometime I need to test how an application response to certain HTTP status code. Testing handling of non-200 status is quite important for API integration. I came across a handy tool at https://httpstatus.io/mocking-data. Unfortunately it does not support mocking of non-standard status code, e.g. "499".

So I resort to writing and hosting a simple service myself. This is how it works:

# RFC 2324 defined code
curl -i https://http.mrleong.net/418
# Custom status code
curl -i https://http.mrleong.net/499

Recommendations

  • Understand the meaning of each status code. (Reference: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status)

  • Whenever possible, use the standard status codes. Making sure the situation matches the status reason. For example, an API client query for an unregistered customer ID, 404 would be a suitable code.

  • If you really need to define custom status code, stick to 2xx, 3xx, 4xx, 5xx. Most of the time you only need 200, 4xx, and 5xx.

    • Use 4xx for client-side errors (e.g. authentication, authorization, validation failure)

    • Use 5xx for server-side error (e.g. unable to connect 3rd party services, DB issue)

Known Issue

My service does not work well with 1xx codes. If anyone has any suggestion for improvement, feel free to discuss it in the comment section.

CodeTalk

Part 3 of 5

In this series, I will share code that is useful for solving problems. Talk code and dream code.

Up next

PHP: Recursively Delete Old Files

Useful for purging backup/temporary/cache files after a certain period of time.

More from this blog

Hong's Tech Blog

110 posts

The blog is older than you know. I prefer counting from the emergence of one integral anomaly to the emergence of the next, in which case this is the forth version.