I have to create a middleware API which a functionality to check for a key present in my database. If the key exists then it should simply fetch it(GET method). If not, then the API should create the key and its value in the database and return that(POST method). So since we have 2 fundamentally different methods being combined in this API, is it correct to do so? What should be the best way to design such API?
3 Answers
Don't combine them.
Return zero results from your GET
method if you the record doesn't exist. Then in the client, if you receive zero results, POST
the needed information to another API endpoint.
Combining the two ideas into one will create a hard to understand system. Your system should be deterministic, i.e. you can always know the result of every call before you call it.

- 4,860
- 1
- 29
- 39
One way to look at your API is to forget about the underlying database, but think about how an API client uses it.
If an API client does a GET request, 2 things happen:
- The existing record is returned
- A new record is created and is returned
A client might not actually care if 1 or 2 happened. For the perspective of the client, it might look like the resource always existed (even if it was technically just created).
So as long as there's no extra information that must be sent along with a POST request, it might be fine to use a GET request for both cases.

- 93,428
- 18
- 118
- 189
I don't know about your situation, typically it is best to have your get and post seperated. Though, if your client thinks that it needs to create a record and then posts the data, i dont see the problem with returning the resource and a 409 for the resource already existing. Here is a similar question HTTP response code for POST when resource already exists
Then the client can handle the 409 differently or the same as a 200 depending on your needs.

- 1,764
- 2
- 15
- 35