top | item 23515857

Ask HN: Best Way to Mock APIs in 2020?

71 points| HiddenCanary | 5 years ago | reply

I'm looking for a good way to Mock APIs for a sideproject, so far I haven't found any solution that has blown me away and I'm wondering If I'm missing anything.

I'm curious what people recommend for the best way to Mock APIs?

59 comments

order
[+] triztian|5 years ago|reply
I've found mitmproxy (https://mitmproxy.org) in reverse mode really useful. I'm a mobile dev and when the backend work is still pending I usually mock the backend requirements by selectively patching or adding endpoint support, it can be used like so:

    mitmproxy --mode reverse:https://my.privateapi.com -s ./path/to/mockscript.py

This allows me to implement most of the UI and server interactions w/o being blocked by server work.
[+] peheje|5 years ago|reply
Can someone explain to me what this is all about? Shouldn't you hide all your API calls behind an interface, and then mock that interface? Dependency inversion principle, depend upon abstractions and all that.
[+] pydry|5 years ago|reply
I've gone through this process a few times:

1) Join a project and fume about how they didn't write nice, clean, "testable" code.

2) Build some sort of integration testing framework that also mocks out REST API calls relatively cheaply (e.g. using recording/playback against a live system).

3) Realize that I can now refactor the code such that it is nice, clean and more easily "unit testable".

4) Realize that with an effective and easy to use, fast integration testing framework the lack of dependency inversion doesn't bother me nearly as much as it used to.

5) Wonder if dependency inversion is actually more of a hack to deal with the sheer utter crappiness of unit tests... and whether making vast architectural changes to code in order to accommodate the sheer ineffectiveness of the current state of test tooling is really the height of wisdom after all.

In a number of these projects there were noises about rewriting the whole damn thing in a different language (usually because management wanted to consolidate hiring around fewer languages), and it occurred to me that it would actually be kind of great to write tests where the entire implementation including the language itself could be swapped out without really changing the tests.

[+] anonymoushn|5 years ago|reply
Some reasons not do to that:

- Now it's harder to navigate my codebase because I introduced an extra layer of indirection everywhere only for the sake of testing.

- If there is some difference between how the actual protocol client and actual upstream behave and how my fake interface behaves in test, my tests will be wrong, and I will find out when I push to prod. If my tests exercised the actual code that speaks the actual protocol to a fake upstream, I may have caught the issue in the tests.

- If I ever want to replace the process entirely with a completely different one, I must now throw away my tests. If my tests tested the end-to-end behavior of the system, I would be able to keep my tests.

[+] emilsedgh|5 years ago|reply
I personally am not a fan of too many abstractions.

If the only reason for abstraction is testing, then mocking an interface seems like a more valid choice to me.

[+] djohnston|5 years ago|reply
What does mocking an interface mean, like a mock implementation?

How is that different then defining an API and then having stub methods on the front returning pretend data?

[+] bspammer|5 years ago|reply
Definitely you should do that, but it's still useful to have automated API tests too. That way you can upgrade client libraries risk free (and even automate these upgrades with tools like https://dependabot.com/). If your tests are green then you're good.
[+] HiddenCanary|5 years ago|reply
For me, this is part of the design and development phase to help me plan the API structure and also to provide test API data mocks to the frontend, so that frontend doesn't have to wait on the backend to finish development before they can start.
[+] robjan|5 years ago|reply
Depends how advanced the mocking behaviour requirements are. For most projects, I find json-server sufficient.

Remember that perfect is the enemy of good enough. If you're looking to be blown away by your mock server you may never get round to building your product.

[+] nerdywordy|5 years ago|reply
https://miragejs.com/ is a great complement to frontend first development. Some folks on my team use it and love it. I tend to dev from back to front so I don't run into the need as much. If I do I typically just mock a JSON response in my frontend call function. Depending on the need I'll sometimes set the call to return an error response as well.
[+] jcpst|5 years ago|reply
For a side project? I think that makes a difference here.

What I’ve been doing lately, in my own time outside of work, is setting up a postgres DB, pointing postgraphile to it, then I have the API out of the way.

From there, if I’m consuming that API in a statically-typed language, I’ll look at generating the models I need from the graphql schema with quicktype.

That process is usually quick enough that there’s no reason to mock.

I suppose if I was doing UI first, I would just have the repository layer that’s abstracting my calls to whatever just have a function that returns a dumb static object in the shape I expect.

[+] kahrensdd|5 years ago|reply
There are lots of variations depending upon your use case.

For unit testing and CI you may want mock objects that are implemented in the same language as your code. Google search for "mock object <language>". That's where you'll find Mockito (Java) or Mocha Spy (NodeJS) or Testify (golang). This list never ends.

Specifically for unit testing of a UI, you may want your browser driver to handle this, ex: Cypress has built-in support for mock AJAX endpoints. https://docs.cypress.io/guides/guides/stubs-spies-and-clocks...

If you want an endpoint you can call, Postman has a feature for this, there are several others like this in the comments (JSON Server, mmock, mountebank, etc.). https://learning.postman.com/docs/postman/mock-servers/setti...

If you need to capture traffic, check out goreplay or mitmproxy: https://github.com/buger/goreplay https://docs.mitmproxy.org/stable/

There is a whole class of "VCR" projects for recording traffic, these tend to be language specific (VCR is in Ruby), but there are ports to other languages: https://github.com/vcr/vcr https://github.com/bblimke/webmock

The vendor products tend to be labelled Service Virtualization. I used to work for one of those companies, ITKO, we were acquired by CA Technologies (now Broadcom) in 2011. There are vendor products from Micro Focus, Tricentis, Broadcom, Parasoft, etc.

It's important to think about your use case: local development, unit testing, CI, integration testing, performance testing, recording vs. programming, protocol support, payload support, etc. Many of the tools focus on just a subset of these areas.

[+] baggsie|5 years ago|reply
I've found Hasura to be great for this, maybe slightly more longer to set up but you get a full CRUD graphql setup for little effort.
[+] mdaniel|5 years ago|reply
I readily admit I haven't evaluated every one of the comprehensive URLs in this thread, but back when I was doing integration work between my project and both GitHub and Jira, I found the scripting support in SoauUI (https://github.com/smartbear/soapui/tree/release-5.5.0) allowed me to model some dynamic behavior, and use the fallback responses when I didn't care about specifying every single one of them

Despite its name, SoapUI has strong support for REST, and with a little massaging maybe even GraphQL also

[+] xgenecloud|5 years ago|reply
If you have a database - try this https://github.com/xgenecloud/xgenecloud

Automatically generates REST & GraphQL APIs within seconds from your database schema.

Here is a demo on how to create 8000+ REST APIs within 10 seconds - https://youtu.be/NtCwnlLudnk

Not just mock - you may even consider writing the full backend on it.

Im the creator - happy to answer any questions.

edit : added demo link

[+] disposedtrolley|5 years ago|reply
If the API provider supplies an OpenAPI definition, you can give API Sprout a try. It’ll parse the definition and spin up a mock server returning the example data you want. You can also modify the OpenAPI definition manually if you need different data to be returned.

https://github.com/danielgtaylor/apisprout

[+] jacobr|5 years ago|reply
Haven’t tried it yet, but https://www.npmjs.com/package/msw looks very interesting. It uses Service Workers in the browser to intercept requests to the APIs, instead of running a real mock server.

There’s support for mocking in Node as well for SSR and jsdom tests.

[+] pinacarlos90|5 years ago|reply
Use swagger-openAPI3 and generate a spec. You can then use the spec to spin up clients or import to a API management tool and produce mock data, with support for authentication and more. I recommend using swashbuckle (for .netCore) if you already have the code for your API, it allows you to quickly produce spec from code.
[+] coold|5 years ago|reply
I'm using Wiremock
[+] thiht|5 years ago|reply
Shameless plug: I developed Smocker[1] for exactly this use case. It's not the only solution but we have a few features not present anywhere else that matched exactly our use case.

Hope it can help you :)

[1]: https://smocker.dev