Creating Mock API Server in Fsharp Using Suave
As part of the current assignment in my day job, I am working in a web application which integrates with an another web application via web APIs. The backend calls the exposed web APIs and does some business logic. Due to some technical limitations, we are not able to setup a development environment of the Web APIs so we have decided to create a mock API server during the development and replace it with the real one in the production.
Since it’s just a mock API server, we don’t want to spend much time on it. Thanks to the awesome light-weight fsharp library Suave we have made it in just 15 minutes!
In this blog post, I will be sharing how we have achieved it. As a sample, we will mock the GitHub API.
Getting Started
Create a new fsharp console application project “GitHubMockApiServer” in Visual Studio and install the suave nuget package.
To keep it short we are going to mock only two GitHub APIs
- Get a single user - /users/:username
- List user repositories - /users/:username/repos
Creating the mock APIs
The first step is getting the sample response for these APIs and save them in separate JSON files. In this example, I’ve created these using my GitHub username and added to the project as below.
After adding, change the “Copy to Output Directory” property of the both the files to “Copy always”
Open the Program.fs and update it as follows
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
Short and Sweet! Now you can hit this mock GitHub APIs without worrying about its rate limits
The json
function reads the sample JSON file, then removes the line breaks and return the HTTP 200 response with the content type as “application/json”
The nice DSL in suave enabled us to configure the routes without giving much works to our hands :-)
Mock APIs in action
Summary
This work is inspired by Scott Wlaschin’s blog post series on Low-risk ways to use F# at work. I am glad to find one more low-risk way to use F# at work and I believe it would help you in future. You can find the sample code in my blog-samples GitHub repository.