<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Mohamed Hassanin on Medium]]></title>
        <description><![CDATA[Stories by Mohamed Hassanin on Medium]]></description>
        <link>https://medium.com/@imagdy91?source=rss-118e9ee4b6db------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*rlNEYnJT9whm-L-t.</url>
            <title>Stories by Mohamed Hassanin on Medium</title>
            <link>https://medium.com/@imagdy91?source=rss-118e9ee4b6db------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 16:07:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@imagdy91/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Mocking your own RESTful APIs on Sandbox]]></title>
            <link>https://medium.com/@imagdy91/mocking-your-own-restful-apis-on-sandbox-174d9c8ea85e?source=rss-118e9ee4b6db------2</link>
            <guid isPermaLink="false">https://medium.com/p/174d9c8ea85e</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Mohamed Hassanin]]></dc:creator>
            <pubDate>Wed, 05 Sep 2018 14:44:05 GMT</pubDate>
            <atom:updated>2018-09-05T15:25:52.559Z</atom:updated>
            <content:encoded><![CDATA[<p>Are you a Frontend/Mobile Developer who always says “We have a bottleneck because of the Backend” ? 😇.. Well, you can’t use this excuse anymore 😒, because now you can be your own Backend Developer with just some basic programming knowledge (Which you should possess if you’re a Frontend/Mobile Developer). 🤷‍♂️</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F10y6mMS2zYqefm%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fmichael-cera-holy-shit-gone-crazy-10y6mMS2zYqefm&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F10y6mMS2zYqefm%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="234" frameborder="0" scrolling="no"><a href="https://medium.com/media/165d66825c3ba6c2bbd710c7e0c3ed3f/href">https://medium.com/media/165d66825c3ba6c2bbd710c7e0c3ed3f/href</a></iframe><p>The most popular types of APIs or Webservices are of course <strong>REST</strong> and <strong>SOAP</strong>, but we’re gonna focus only on <strong>RESTful </strong>APIs on this article because remind me again when was the last time you used <strong>SOAP</strong> ? 🤔(You can check this <a href="https://nordicapis.com/rest-vs-soap-nordic-apis-infographic-comparison/">Infographic</a> to know the difference between <strong>REST</strong> and <strong>SOAP</strong> and when it’s better to use any of them).</p><p>Let me introduce an amazing tool called Sandbox. (<a href="https://getsandbox.com/">https://getsandbox.com</a>)</p><p>The tool simply gives you the ability to create your own very sophisticated APIs on the cloud and even allows you to manipulate an on-the-fly Database.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FvKNoZ2ZgKoIwM%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fsong-like-mid1980s-vKNoZ2ZgKoIwM&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FvKNoZ2ZgKoIwM%2F200.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="261" frameborder="0" scrolling="no"><a href="https://medium.com/media/af8ced6c01dc288ac8cad239d5280f09/href">https://medium.com/media/af8ced6c01dc288ac8cad239d5280f09/href</a></iframe><p>Sandbox provides you with the option to import the APIs represented with one of the following options, and you can alter/extend them as you wish.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*vw3GOzay_fWfeLJTiYaxcA.png" /></figure><p>We’ll go with the option <strong>Blank </strong>for now, just because I wouldn’t even have to be here if I happen to have a <strong>Swagger</strong>. 🤦‍♂️</p><h3>Getting Started</h3><p>When you choose option <strong>Blank</strong>, it’s not as blank as you think, <strong>Sandbox</strong> actually creates 4 template APIs for you.</p><p>Unfortunately, it’s not your lucky day as we’re going to delete all the templates from the “x” button on the right side and start everything from scratch..</p><p>Because you know..</p><blockquote>Give a Man a Fish, and You Feed Him for a Day. Teach a Man To Fish, and You Feed Him for a Lifetime</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*siIsZlQoou-zvYatnluIPA.png" /><figcaption>Sandbox Default Dashboard, remove the template APIs by clicking on the “x” button on the right side of each API</figcaption></figure><p>After deleting everything, let’s create our own APIs by clicking on “Add new route”</p><p>You will find a template request for you, let’s just call our API “status” by adding it to the Path and leave everything with the default so that it would be a REST GET API with Content-type: application/json and then click <strong>Create</strong>.</p><p>Sandboxes are run in the cloud so changes you make are automatically and instantly deployed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rH3ax57f4XyzmKyXJudLXA.png" /><figcaption>Sample GET API</figcaption></figure><p>The API as you can tell returns a simple json response saying that status is <strong>OK</strong></p><p>Your mock services are made available at your unique URL which is your Sandbox name appended with .getsandbox.com. Open a terminal:</p><pre>$curl -X GET -H &quot;Content-Type: application/json&quot; http://{{ your-sandbox-name }}.getsandbox.com/status</pre><p>And you’ll get this response:</p><pre>{ &quot;status&quot;: &quot;ok&quot; }</pre><p>And Voilà! You have created your first API</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F3o6ZtkTtNTSngwbh1m%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fpaleycenter-3o6ZtkTtNTSngwbh1m&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F3o6ZtkTtNTSngwbh1m%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/54c1a644a281438d6783fbda864c63a3/href">https://medium.com/media/54c1a644a281438d6783fbda864c63a3/href</a></iframe><h3>HTTP Request Handling</h3><p>At some point you need to achieve more things that just knowing that <strong>status</strong> is <strong>OK</strong>, So we have to make our APIs a little bit more dynamic.</p><p><strong>Sandbox </strong>gives you full control on the generated <strong>Javascript</strong> code for each API you create using the wizard.. Wait, What! <strong>Javascript</strong>?</p><p>Yes, it’s that language you hated most at college. But guess what? not anymore!</p><p>HTTP request messages are handled by defining requests using Sandbox.define() and providing a URL path, HTTP method and a callback function that holds the request and the response objects. For example:</p><pre>Sandbox.define(&#39;/users&#39;, &#39;GET&#39;, function(req, res) {</pre><pre>...</pre><pre>}</pre><p>or for a POST method:</p><pre>Sandbox.define(&#39;/users&#39;, &#39;POST&#39;, function(req, res) {</pre><pre>...</pre><pre>}</pre><p>The <strong>Request</strong> (req) object contains all the data attached to the coming request like headers, body and parameters. and we then use the <strong>Response</strong> (res) object to build responses to the request.</p><p>Let’s do something useful then… 💪</p><p>Create a new <strong>GET</strong> route and call it /users, edit the route and replace the Route Definition with the below code..</p><pre>var users = [{<br>    username: &quot;user1&quot;,<br>    email: &quot;user1<a href="/service/mailto:dave@gmail.com">@</a>mydomain.com&quot;<br>}, {<br>    username: &quot;user2&quot;,<br>    email: &quot;user2@mydomain.com&quot;<br>}]</pre><pre>return res.json(users)</pre><p>Keep in mind that you’re already inside the implementation of the block function(req, res) so you already have access to req and res objects</p><p>Click <strong>Update</strong> and let’s try our new request in terminal</p><pre>$curl -X GET -H &quot;Content-Type: application/json&quot; http://{{ your-sandbox-name }}.getsandbox.com/users</pre><p>and you get the following response:</p><pre>{</pre><pre>&quot;username&quot;: &quot;user1&quot;,</pre><pre>&quot;email&quot;: &quot;user1@mydomain.com&quot;</pre><pre>},</pre><pre>{</pre><pre>&quot;username&quot;: &quot;user2&quot;,</pre><pre>&quot;email&quot;: &quot;user2@mydomain.com&quot;</pre><pre>}</pre><p>Pretty easy, huh ?</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F3ohs88j0jPszpGCbYY%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fsmile-face-3ohs88j0jPszpGCbYY&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F3ohs88j0jPszpGCbYY%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/e0b110c332b3945f91def22cb17a7ad1/href">https://medium.com/media/e0b110c332b3945f91def22cb17a7ad1/href</a></iframe><p>Let’s add support for filters based on the user’s age using Query Parameters, req.query is an object containing the parsed request query string, so if we submit a request of `GET /users?age=26` we can access the age value inside the function block by req.query.age</p><p>Extend your GET users API Route Definition like below..</p><pre>var users = [{<br>    username: &quot;user1&quot;,<br>    email: &quot;user1<a href="/service/mailto:dave@gmail.com">@</a>mydomain.com&quot;,<br>    age: 30<br>}, {<br>    username: &quot;user2&quot;,<br>    email: &quot;user2@mydomain.com&quot;,<br>    age: 26<br>}]</pre><pre>if (req.query.age) {<br>  // convert req.query.age from String to a Number before filtering<br>  return res.json(_.filter(users, { &#39;age&#39;: Number(req.query.age) }))<br>}</pre><pre>return res.json(users)</pre><p>We here used a <a href="https://lodash.com/docs">LoDash</a> function (<strong>a.k.a</strong> Higher Order Functions in Swift) which is _.filter to filter the users array according to the age that’s matching the number in the query parameter.</p><p>Let’s give it a try:</p><pre>$curl -X GET -H &quot;Content-Type: application/json&quot; http://{{ your-sandbox-name }}.getsandbox.com/users?age=26</pre><p>We get:</p><pre>{</pre><pre>&quot;username&quot;: &quot;user2&quot;,</pre><pre>&quot;email&quot;: &quot;user2@mydomain.com&quot;,</pre><pre>&quot;age&quot;: 26</pre><pre>}</pre><p>Also Route/Path parameters can be used in GET requests, let’s create a new GET route on Sandbox and call it /users/{username} the req.params object will then contain the property mapped to the named path parameter, so in this case the username value for the request would be in req.params.username</p><p>Replace the /users/{username} route definition with the below code:</p><pre>var users = [{<br>    username: &quot;user1&quot;,<br>    email: &quot;user1<a href="/service/mailto:dave@gmail.com">@</a>mydomain.com&quot;,<br>    age: 30<br>}, {<br>    username: &quot;user2&quot;,<br>    email: &quot;user2@mydomain.com&quot;,<br>    age: 26<br>}]</pre><pre>// respond with the user or an empty object if user doesnt exist<br>return res.json(_.find(users, { &#39;username&#39;: req.params.username }) || {})</pre><p>Here we used the <a href="https://lodash.com/docs">LoDash</a> function _.find to query the array for a username matching our path parameter.</p><p>Let’s try it again:</p><pre>$curl -X GET -H &quot;Content-Type: application/json&quot; http://{{ your-sandbox-name }}.getsandbox.com/users/user1</pre><p>Response:</p><pre>{</pre><pre>&quot;username&quot;: &quot;user1&quot;,</pre><pre>&quot;email&quot;: &quot;user1@mydomain.com&quot;,</pre><pre>&quot;age&quot;: 30</pre><pre>}</pre><p>By default, all responses return a 200. If a number is provided as the only parameter to res.json a response body string is assigned for you. For example, 400 will respond with &quot;Bad Request&quot;. We&#39;ve specified a custom error message in the below example.</p><pre>res.json(400, { error: { message: &quot;A custom error message&quot; } })</pre><h3>Stateful Responses</h3><p>In order to have a well integrated system, we need to make our APIs more dynamic and not just sending canned responses.</p><p>For this, <strong>Sandbox </strong>provides a global state object for persisting data.</p><p>Let’s create a new <strong>POST</strong> route and call it /users</p><p>Edit the route and select “View in full code editor” from the Route Definition.</p><p>A new editor will open with a <em>main.js</em> file, locate the implementation of the newly created /users route and replace it with..</p><pre>// create state.users if it doesn&#39;t exist<br>state.users = state.users || []</pre><pre>Sandbox.define(&#39;/users&#39;, &#39;POST&#39;, function(req, res) {<br>// validate username is present<br>if (req.body.username === undefined) {<br>  return res.json(400, { status: &quot;error&quot;, details: &quot;Missing username&quot; })<br>}</pre><pre>state.users.push(req.body)</pre><pre>return res.json({status: &quot;ok&quot;})</pre><pre>})</pre><p>We initialize the state object before all the routes to make sure it’s always accessible, think of it as a Database on-the-fly.</p><p>Try it:</p><pre>$curl -X POST -d &#39;{&quot;username&quot;:&quot;user3&quot;}&#39; -H &quot;Content-Type: application/json&quot; http://{{ your-sandbox-name }}.getsandbox.com/users</pre><p>You get:</p><pre>{</pre><pre>&quot;status&quot;: &quot;ok&quot;</pre><pre>}</pre><p>Time to update our GET APIs accordingly so it will also read from the state object and not the canned array we already created.</p><pre>Sandbox.define(&#39;/users&#39;, &#39;GET&#39;, function(req, res) {<br>   if (req.query.age)<br> {<br>     // convert req.query.age from String to a Number before comparing<br>     return res.json(_.filter(state.users, { &#39;age&#39;: Number(req.query.age) })) <br>  } <br>   return res.json(state.users) </pre><pre>}) </pre><pre>Sandbox.define(&#39;/users/{username}&#39;, &#39;GET&#39;, function(req, res) {<br>   var user = _.find(state.users, { &#39;username&#39;: req.params.username }) <br>     // respond with 404 if user isn&#39;t found<br>   if (!user) <br>{   <br>   return res.json(404, { error: { message: &#39;User doesnt exist&#39; } })    <br>}   </pre><pre>   return res.json(user)</pre><pre>})</pre><p>By now you might become so proud that you were able to create this sophisticated system but you didn’t realize you’ve added too many dummy users.. Uh oh! 😏</p><p>Time to delete some users from the state object.. Add the following API to your <em>main.js</em> file</p><pre>Sandbox.define(&#39;/users/{username}&#39;, &#39;DELETE&#39;, function(req, res) {<br>   var user = _.find(state.users, { &#39;username&#39;: req.params.username })<br> if (!user)<br> {<br>       return res.json(404, { error: { mesage: &#39;User doesnt exist&#39;}   }) <br> }  <br>   // use Lodash reject to remove the user<br>   state.users = _.reject(state.users, { &#39;username&#39;: req.params.username })</pre><pre> return res.json({status: &#39;ok&#39;})<br>})</pre><p>We use the <a href="https://lodash.com/docs">LoDash</a> fuction _.reject to remove user from state.users</p><pre>$curl -X &quot;DELETE&quot;  http://{{ your-sandbox-name }}.getsandbox.com/users/user3</pre><p>Last but not least, we add an update API to update an existing User using the <a href="https://lodash.com/docs">LoDash</a> _.merge</p><pre>Sandbox.define(&#39;/users/{username}&#39;, &#39;PUT&#39;, function(req, res) {<br> var user = _.find(state.users, { username: req.params.username })<br> if (!user)<br>{<br>      return res.json(404, { error: { message: &#39;User doesnt exist&#39; }})<br>}<br>   // update the user object<br>   _.merge(user, req.body)</pre><pre>   // drop the user and subsequently readd<br>   state.users = _.reject(state.users, { username: req.params.username })</pre><pre>   state.users.push(user)</pre><pre>   return res.json({ status: &#39;ok&#39;})<br> })</pre><p>Give it a go:</p><pre>$curl -X PUT -d &#39;{&quot;username&quot;:&quot;updateduser&quot;, &quot;email&quot;: &quot;updateduser@mydomain.com&quot;}&#39; -H &quot;Content-Type: application/json&quot; http://{{ your-sandbox-name }}.getsandbox.com/users/user3</pre><p>Then try executing the GET /users you will find amazing results!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FD0EjguuQzYr9m%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fcomputer-nerd-geek-D0EjguuQzYr9m&amp;image=https%3A%2F%2Fmedia3.giphy.com%2Fmedia%2FD0EjguuQzYr9m%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="290" frameborder="0" scrolling="no"><a href="https://medium.com/media/0279a14f6c1b4559506b96a738834027/href">https://medium.com/media/0279a14f6c1b4559506b96a738834027/href</a></iframe><p>There are still lots of other features that <strong>Sandbox</strong> can support like: Adding delay to responses and Authentication, but that’s a topic for another day….</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=174d9c8ea85e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>