fabiochiu/medium-articles huggingface dataset:
Frontend journey of Unitz
By: Selçuk Fatih Sevinç
Tags: Programming, Knowledge Management, Side Project, Startup Life, SaaS

Hi, I’m Selçuk, I’m the solo developer and the cofounder of the Unitz.

In the previous post I mentioned a term: developer’s dilemma. Of course there is not such a thing officially; I call the situation like that. If you want to focus actually on a product; however, if you are focusing mostly on the code and architecture, welcome to the developer’s dilemma :)

While I was coding Unitz and projects for the last 1,5 years, I fell into this situation. It is not bad at all but I created the project after 1,5 years, not 3 months, such a waste of time. In the end, I’m close to the architecture and codebase I want but remember that coding is a process; it never ends during the lifetime of your product. Now I’ll try to tell you what I’ve done in the past 1,5 years.

Beginnings…

I came up with the Unitz idea, based on my previous experiences, as I mentioned in the previous posts. I decided to use Node.js and Mongodb for the backend, and it was ok for me. I was not sure about frontend. It would be an app basically, not a regular website. I thought about using Angular, because its object-oriented architecture makes sense to me. React was an option but I didn’t try it, only looked at to the documentation. It was looking bad: what am I writing — Javascript, HTML, XML, wtf?

I read a book for Angular but I was feeling something was wrong with the Angular. It had a high learning curve. I used Backbone-Marionette before but It was not a real option anymore. Finally I decided to go with the classical way, and render the HTML with Nunjucks :)

I started with Nunjucks, and it was ok for the first times. However, it doesn’t give the feeling of an app. One evening I tried a React Native example, demo of an Shoutem UI library. I started playing with React, and started to understand the idea behind it. I was enlightened :)

Let’s “React”!

I decided to change the view layer with React. It was not very easy to convert Nunjucks views to a React app. However I made it. I learned about React but also I did some mistakes with React. I move on with semantic-UI React. I made 4 big refactoring on the codebase. The Unitz projects have the same UI structure, so I converted most of the parts to work with HOC’s. Semantic UI was not enough. I don’t like its grid system, and also I cannot even use the effects of components, because they cannot implement the effects. Then I discovered Ant Design. It has a lot of components, Bootstrap-like grid system and it is good looking. One more refactoring marathon, and today the system is working with Ant Design.

You see, only the view layer costs me for at least 8–9 months. This was my biggest mistake. I wish I tried possible UI alternatives before starting the project.

I’ll keep writing about Unitz and its products. Please, don’t hesitate to leave comments and feedbacks.
【專訪 Omnichat iOS 開發工程師彥婷】從零自學寫 code，到獨立開發產品
By: Hazel Lee 李宛儒
Tags: Startup Life, Talent, Startup, Talent Insights, Engineering Insights

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
Wszczepianie genu innowacji nowym pracownikom
By: Łukasz Cieśla
Tags: Corporate Culture, Intrapreneur, Open Innovation, Intrapreneurship, Startup Life

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
1% Kampagne: matched.io hilft Startups beim Tech-Recruitment.
Tags: Deutschland, Tech, Startup Life, AI, Startup

matched.io | Matchmakers. Reshaping job matching for developers. On a mission to digitize the world 🌍
API VE REST
By: Mustafa Zeren
Tags: Postman, Rest, Rest Api, API, Testing

What is an API?

An API is a set of definitions and protocols for building and integrating application software. API stands for…
Java Spring Boot — More About REST Controller : Returning Object From Controller
Tags: Java, Java Spring Boot, Rest Api, Java Spring

In the previous article, we have developed a simple REST API where we can call an URL from web browser and get a response.

Now we will make something more applicable in real web service use case. When we call an API on a web service, we often want to do some data manipulation. Either we want to get, write, edit, or delete some data. Let’s try to build an API when we can get some data from it.

I will try to make an API that return a list of object. Let’s start from creating a class which will be the object we return. I named this class Student where it has two variable named studentNumber which the data type is an integer, and name which the data type is a string. Also, don’t forget to add the constructor, getter, and setter function.

After that, we make a function and annotate it with @RequestMapping(value=/”students”) annotation to make it accessible via REST request through /students URL. The function will return a list of student objects.

Now for convenient to test our function, let’s just hard code the return of the function.

Finally, when we run the app, we will see the following return. Notice that the return we get is already in JSON format. This is done because we use @RestController annotation at our controller class (the MyController class), so Spring Boot will do the transformation from java object to JSON format for us.
Bulk creation of a resource with Django Rest Framework
By: Osirus Djodji
Tags: Django, Django Rest Framework, Web Development, Rest Api

Django REST framework is a powerful and flexible toolkit for building Web APIs.

Bulk creation in an app or API allow us to create many object in one request.

The first step is to install and setup django rest framework.

Assuming you’re using pip:

pip install djangorestframework

We need to add rest_framework to INSTALLED_APPS in settings.py:

# settings.py INSTALLED_APPS = [

...

'rest_framework',

]

And add the following to your root urls.py file.

# urls.py urlpatterns = [

...

path('api-auth/', include('rest_framework.urls'))

]

Now let’s take a look at the model we’re going to use.

# models.py from django.db import models



class Client(models.Model):

first_name = models.CharField(max_length=30)

last_name = models.CharField(max_length=30)

contact = models.CharField(max_length=30)

email = models.EmailField(unique=True)

address = models.CharField(max_length=30)

We will create a serializer for this model using Django REST’s ModelSerializer helper class:

# serializers.py from myapp.models import Client

from rest_framework import serializers





class ClientSerializer(serializers.ModelSerializer):

class Meta:

model = Client

fields = ['id', 'first_name', 'last_name', 'contact',

'email', 'address']

Next we need to create a mixin that will allow the view to handle an array of JSON objects in the request so that the actual view can process and create new objects in a bulk fashion:

# mixins.py class CreateListMixin:

"""Allows bulk creation of a resource."""

def get_serializer(self, *args, **kwargs):

if isinstance(kwargs.get('data', {}), list):

kwargs['many'] = True



return super().get_serializer(*args, **kwargs)

We can now create a view and make it use the mixin.

# viewsets.py from rest_framework import viewsets



from myapp.serializers import ClientSerializer

from myapp.mixins import CreateListMixin

from myapp.models import Client





class ClientViewSet(CreateListMixin, viewsets.ModelViewSet):

queryset = Client.objects.all()

serializer_class = ClientSerializer

The last step is to set a URL to make the request to.

# urls.py from django.conf.urls import url, include

from rest_framework import routers



from views import ClientViewSet





router = routers.DefaultRouter()

router.register(r'clients', ClientViewSet)

And it do the trick!
Batch APIs in Dropwizard
By: Aviral Verma
Tags: Java, Hibernate, Dropwizard, Rest Api, Batch

We had a use case where we wanted to introduce batch APIs for a handful of PUT endpoints.

A little background: Till now all resource methods(API endpoints) that used to interact with Database had their transaction lifetime governed by @UnitOfWork.

@UnitOfWork: This will automatically open a session, begin a transaction, call <dao-method>, commit the transaction, and finally close the session. If an exception is thrown, the transaction is rolled back.

We wanted the batch endpoints to be able to handle partial failures use-case. For that we needed to catch the exception thrown by the underlying methods. Here lies the catch, since `@UnitOfWork` relies on exception being thrown, we could not catch the exception here. But on the other hand, if we were to throw the exception(that was raised while processing one of the request) the entire transaction would be rolled back, meaning that all the successful entities would too be rolled back.

This is clearly non ideal behavior.

We needed to manually define transactions boundaries and terminal states(when it be would be committed or rolled back). We used Hibernate’s Session API to commit/rollback the session as per our needs.

We ended up with the following structure for our service layer methods:

Session session = sessionFactory.openSession();

try { ManagedSessionContext.bind(session); for (request: requests) {

try {

if (!session.getTransaction().isActive()) {

session.getTransaction().setTimeout(2);

session.getTransaction().begin();

}

response = oneToOneMapper(request);

session.getTransaction().commit();

response.addToSuccessMap(request, response); } catch (Exception ex) {

String errorMessage = ex.getMessage();

response.addToFailureMap(request, errorMessage);

session.getTransaction().rollback();

}

}

} finally {

session.close();

}

return response;

While this solves the problem at hand, the code is cumbersome and gets unmaintainable very quickly. Since we needed to have batch APIs for many resources, the boiler plate would have to be repeated over and over again.

In the next blog, I will try to present a design where we can eliminate the above problems.
Best REST API Practices and Tools
By: Harsh Patel
Tags: Programming, Coding, Rest Api, API, Web Development

How to design a RESTful API server?

The RESTful API server can be built using almost all backup system languages. We will discuss this later in this article. Here we try to understand the RESTful API pattern. What is often needed in the app is CRUD (create, read, update, delete) capability. . These are the four things all apps have. Like creating posts, reading posts, updating posts, and finally deleting posts. In the RESTful API, you will create a path (route) called / post. A typical naming convention uses plurals. As you see CRUD has four methods. thus it needs to assign all the methods. The HTTP protocol has four modes for this issue, namely POST, GET, PUT, DELETE. These methods can be applied sequentially to CRUD action. Here is an example:

GET /posts # Get the posts list

GET /posts/{id} # Get the post with id of {id}

POST /posts # Create post

PUT /posts/{id} # Update the post with id of {id}

DELETE /posts/{id} # Delete the post with id of {id}

The beginning of the route as /post is also often called a collection.

Do not use abbreviated words such as /p for /posts. This makes it difficult to remember what the endpoint does.

Never use verbs in the name of the method. This means that the following routes are not considered RESTful API:

POST /createPost

POST /deletePost

POST /updatePost

HTTP methods are no different when it comes to POST, PUT, and DELETE. But applying POST to all routes makes it confusing.

Why do we need to use plural nouns?

Use singular form can be confusing. Imagine using a route or post but you get all the posts!

Why should we not use the verb in road names?

Use an action in the name of the method will make the final API points much higher than required. But in the case of using HTTP methods on the same route, you have a shorter and easier to understand API.

For example, can we use GET to make a record?

And technically speaking, yes! But it should not be, as the GET method is commonly used to obtain data. And even if you pay attention it makes more sense to “Get that post” to get data for that post instead of calling it “Post that post” to get details of that post.
How is Carrot getting Bitcoin to the next billion people with the help of Forest Admin?
By: Ziad Ghalleb
Tags: Bitcoin, Rest Api, Cryptocurrency, Nodejs, Developer Tools

It is really our sort of secret plan, to get Bitcoin to the next billion people!

Tyler Evans, co-founder & CTO of BTC Inc.

The mission at hand is daunting, if not impossible. But those who have met Tyler Evans know he wouldn’t flinch at such a challenge.

Tyler is the co-founder and CTO of BTC Inc — the media group behind Bitcoin Magazine, providing news and commentary on Bitcoin and blockchain technology since 2012 to millions of readers across the globe. With a deep background in the technology and an enthusiastic community, BTC Inc. was in the perfect position to build the next on-ramp for Bitcoin.

In 2020, he and his team at BTC Inc. decided to launch Carrot, a rewards platform where users can earn bitcoin simply by supporting the brands and creators they love. Creators of all sorts (writers, podcasters, open-source collectives…) can publish challenges to be carried out by their audiences and offer bitcoin for their completion.

For its public release, Carrot chose Forest Admin to build its admin panel. Here’s why and how they did it.

Carrot needed serious internal tooling to launch its app 🚀

Carrot’s alpha phase saw it distribute millions of sats* to more than 10,000 users, proving the demand for a micropayment rewards platform.

Launching its public release however, is a different matter. “We needed to stop interacting directly with the database and APIs and build the right set of internal tools for our team”, said Tyler. This would prove critical for the Carrot team to provide responsive customer support at scale, mainly:

Reviewing the challenges and bounties sent by creators

Moderating user submissions to the challenges

Triggering bitcoin payouts for the winning submissions

Fortunately, Forest Admin was here to help.

The day-to-day operations on Forest Admin 🌲

Reviewing the bounties sent by creators

The first conversations we had with Carrot revolved around making the bounty creation process as streamlined as possible. For this to happen, external partners had to be granted access to Forest Admin to submit challenges with little help or no support.

Leveraging Forest Admin’s team-based permissions, Carrot restricted their access to a user-friendly form where it was possible to write a description, set the reward size and upload a few images.
Rest API dengan FastAPI dan Elasticsearch
By: Nasri Adzlani
Tags: Fastapi, Rest, Rest Api, Elasticsearch, Python

FastAPI adalah sebuah framework python yang digunakan untuk membangun API(). FastAPI merupakan salah satu framework python yang memiliki performa bagus dalam membangun API. Bahkan lebih dari itu, dalam documentasinya yang bisa kita lihat disini, FastAPI memiliki banyak kelebihan lain.

Elasticsearch adalah salah satu database yang masuk ke dunia NoSQL dengan fokus di search engine database. Elasticsearch ditenagai oleh Apache Lucene yang juga merupakan search engine database yang memiliki query low level. Elasticsearch memiliki query yang lebih mudah untuk digunakan karena berbasis RESTful.

bahan yang dibutuhkan antara lain

🔹 pip install fastapi uvicorn 🔹 pip install fastapi 🔹 pip install elasticsearch

Jika kedua library di atas sudah terinstall dengan benar, saatnya kita mencoba membuat API. Kita buat sebuah file dengan nama main.py,

import yang dibutuhkan

from elasticsearch import Elasticsearch

from fastapi import FastAPI

import uvicorn

Deklarasi yang dilakukan

app = FastAPI()

es = Elasticsearch('http://localhost:9200/')

Macam fungsi di FastAPI

@app.get("/field") --> Untuk ambil value

@app.post("/field") --> Untuk Ingest / Update

@app.put("/field") --> Untuk Membuat Index

@app.delete("/field") --> Untuk Menghapus

Configure

if __name__ == "__main__":

uvicorn.run(app, host="localhost", port=8899) -> Bisa edit Port

Full SourceCode

from elasticsearch import Elasticsearch

from fastapi import FastAPI

import uvicorn

import json



app = FastAPI()

es = Elasticsearch('http://localhost:9200/')





@app.get("/get_account")

def read_root():

data = es.search(index="ta_identity",body={"query":{"match_all":{}}})

hits = data['hits']['hits']

return hits



@app.get("/search_account")

def search_id(username: str, password: str):

data = es.search(index="ta_identity",body={"query":{"bool":{"must":[{"match":{"data.id":username}},{"match":{"data.password":password}}]}}})

return data['hits']['hits']



@app.post("/register_account")

def register(name:str,username:str,email:str,password:str,number:str):

total = es.search(index="ta_identity",body={"query":{"match_all":{}}})

totals = total['hits']['total']

val = totals['value']

newId = val + 1

data = es.index(index="ta_identity",id=newId, body={"data":{"name":name,"id":username,"email":email,"password":password,"number":number}})

return {"status":"data has been created"}



@app.delete("/delete_account")

def delete_account(username:str):

get_id = es.search(index="ta_identity",body={"query":{"match":{"data.id":username}}})

data = json.dumps(get_id['hits']['hits'])

x= json.loads(data)

id = x[0]['_id']

es.delete(index="ta_identity", id=id)

return "delete "+id+" has success"



if __name__ == "__main__":

uvicorn.run(app, host="localhost", port=8899)

Thanks.
Mockoon CLI is now available!
By: Guillaume Monnet
Tags: Api Development, Rest Api, Prototyping, API, Developer Tools

After months of work, Mockoon CLI is available in beta 🚀. You can now deploy your mock APIs in all your headless and automated environments. A server, your favorite CI environment, in a GitHub Action, in the Windows Subsystem Linux, you name it!

Like the main application, the CLI is free and open-source. It supports most of Mockoon features, and we tried to make it as fast as possible.

You are one command away to using it. Check the installation instructions, and most of all, let us know what you think and what we could improve on the official forum.

How does it work

The CLI takes a Mockoon data export file and runs the specified environment. You can either provide the data as a local file or a URL where you host it.

You can also list the running mock API processes to get some information about them (port, PID, CPU, memory, etc.) or stop them completely.

Mockoon CLI supports all of Mockoon’s features: templating system, proxy mode, route response rules, etc.

It’s also compatible with your data files in an older format as it automatically migrates them before running the mock.

Implementation details

We chose to create an NPM package as it is a widely used and well-known format. It’s also the technology we know best, and we wanted to be sure to create something simple to use, fast and lightweight.

Before actually working on the CLI, we needed first to extract a lot of code from the main application into a new library. Luckily, this part of the main application was already relatively independent. But we still had some challenges and learned a lot about creating a Typescript library 😄.

Under the hood, we used Typescript (as for the main application and the library), Oclif to create the command-line tool, and PM2 to manage your mock API processes. It means that, while we wrap our CLI around all of PM2 commands, you can leverage everything PM2 has to offer if you are used to it!

Closing thoughts

The CLI was our small 2020 challenge. The biggest struggle was to achieve this while having a full-time job and an infinite list of things to work on for this project: content, features, support, etc. But we like challenges 😅.

We were initially planning a beta release for November. It seems the initial estimation wasn’t that off!

We hope that you will love using this tool as much as we loved creating it!

One of the oldest requests from our users ( September 2018! 😱) is now closed, but this is just the beginning! More improvements are already in the pipe. Stay tuned!
One Rest API for your Lifetime Salesforce Implementation with Flow Builder as Controller
Tags: Flow Builder, Rest Api, Salesforce, Apex

Hi Folks, in this article, I’d like to show you how to reuse one Rest Apex Class (+test class) for your lifetime Salesforce implementation.

For those who still not see my article about JSON Parsing in Salesforce Flow, I would suggest you to visit here and here to see how I managed to parse JSON inside Flow Builder because in this article, I will use those components to process inbound data from the rest API.

You may already know that, we can launch Flow directly from Rest API from this official Salesforce Documentation. So the question is, why would I use this method if Salesforce already has default way to launch Flow from Rest API? My personal answers are:

1. That method only support 1 HTTP method, that is POST. And sometimes, we need to use other method when we’re dealing with Salesforce Rest API

2. If you use Official Salesforce method, you’ll not able to custom your own JSON Structure, you’ll have to follow their pattern. And sometimes, that pattern won’t work for your integrated system (or I’d say, its a very awkward structure)

Okay okay, so what solutions am I offering here?

My solutions here are to:

1. Have one Rest Apex Class (+test class) that basically would able to control all of your rest requests (And every time you want to expose new function, you just need to update the flow and don’t need to add new test class)

2. Route the flow functions based on path you set in your flow builder

3. As you may already know, Flow has functionality to send error message to admin when there’s something wrong with your flow. So you’ll immediately notified if there’s something wrong with your integration

4. Supports POST,GET,DELETE,PUT,PATCH methods

5. Able to catch request headers in your flow

6. Able to have dynamic JSON structure

So, here are the steps you need to do to setup that solutions:

a. Install this package which contains OneRest Class, OneRest Test Class, And Main controller for your Rest API. : https://login.salesforce.com/packaging/installPackage.apexp?p0=04t2w000009F5cg (Don’t forget to change login to test.login if you want to install in Sandbox)

Source Code: https://github.com/munawirrahman/OneRest

b. After you installed that Package, congratulations, you already have your first rest with ping pong functionality

Image1: OneRest is the default path name for your installed package, feel free to change it in the apex class (and test class) if you need to

c. After you already installed that package, you’ll have an AutoLaunched Flow like this

Image2: Initial installed flow

Image3: Decision element, as your router based on path

Image4: How to return pong

Image5: Return error code 400 if no path found

Image6: Return 400 if no path found

d. Here are the variables that you can use to route and process the request
Django rest framework
By: Omid Esmaeili
Tags: Class Based Views, Django, Rest Api, Django Rest Framework

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
REST API 🚀 — So called a Back-end system 🖥️
By: Mohammad Fayaz
Tags: Database, Rest Api, Social Media, Web Server, Https

How things work in real-world?

By observing the above picture you might have got an idea what it is 🙄. If not, let me tell you what’s happening 🧐. Let’s take an example to understand this concept. In your student life, you must have done anything like

Social Media users

Posted pictures in facebook/instagram Chat with your friends over WhatsApp, Watched YouTube videos Checked your academic results online. Bank transactions

But ever tried to understand how they work? 🤔 Obviously they happen with the help of Internet, but there’s something else involved to accomplish that task. You might have guessed it 😝. Yeah that’s a Web Server.

Software engineers 🧑‍💻 have configured/trained a computer(web server) to respond with certain things when the user requests certain thing. Assume a situation, when you send a message ✍🏻 to your friend over WhatsApp, your friend instantly gets a notification 🤳🏻. Well, how does that happen?🤷‍♀️ is someone sitting there 🦸🏻 and waiting for me to send a message to my friend so that he can quickly run 🚴🏻‍♀️ and deliver the message. Only a superman or wonder women can do that right. But there billions of people 👩‍👩‍👧‍👧 around the world and often send billions of WhatsApp messages per day.

Or assume like your friend already had messages in his mobile even before you sent them to him. Well this could never happen 🙅‍♂️, no one can accurately predict the future and do all these things. Then how do these Software Engineers 🧑‍💻 make it possible️🤷‍♀️ ?

To understand this concept we should first understand Server-Client architecture. In the end we’ll understand the vital role of REST API.

What is Server-Client architecture?

Consider the client as WhatsApp application on your phone and let’s understand how this works…

Clients

Devices used by people in daily life, like a mobile, laptop…

Internet

A medium which connects clients to a known server.

Web Server

Just another computer which serves data over Internet.

Database

An engine which stores data in a particular format and gives the web-server the capability to perform operations on that data.
Create JSON problematically using JAVA program
Tags: Java, Clients, Json Api, Rest Api, Json

To know more about JSON , read “What is JSON and Understanding JSON syntax with simple example” and “Cloud Technologies”

In this post, we will show you how to create a simple JSON by writing code in JAVA,

$ vim simpleJsonObjectExample.java import org.json.simple.JSONObject; public class simpleJsonObjectExample {

public static void main(String args[]) {

JSONObject myObject = new JSONObject();

myObject.put("myname", "lynxbee");

myObject.put("myurl", "www.lynxbee.com");

System.out.println("We created JSON as example : " + myObject);

}

}

Here, the JSON object is created as,

JSONObject myObject = new JSONObject();

now, the JSON elements can be added to this object as,

myObject.put("myname", "lynxbee");

Compile this program using javac compiler in Ubuntu as,

$ javac simpleJsonObjectExample.java

Error we received when tried to compile this program on Ubuntu,

javac simpleJsonObjectExample.java

simpleJsonObjectExample.java:1: error: package org.json.simple does not exist

import org.json.simple.JSONObject;

this error means, there is no JSON package is installed on your Ubuntu machine, so lets try and resolve this error…

$ sudo apt-get install libjson-simple-java

you can see this JSON library is installed as,

$ ls -alh /usr/share/java/json*

/usr/share/java/json-simple-2.3.0.jar -> json-simple.jar

/usr/share/java/json-simple.jar

Now we need to add this library to classpath as,

$ export CLASSPATH=$CLASSPATH:/usr/share/java/json-simple.jar $ echo $CLASSPATH

:/usr/share/java/json-simple.jar

Now, lets again compile this program as,

$ javac simpleJsonObjectExample.java

Now, if we run the compiled JAVA program, we can see that we created simple JSON with only one object as below,

$ java simpleJsonObjectExample

We created JSON as example : {"myname":"lynxbee","myurl":"www.lynxbee.com"}

This post was originally submitted at “Example of creating simple JSON in JAVA”
Why REST API 🚀 and modeling a perfect one 🧑🏼‍💻
By: Mohammad Fayaz
Tags: Database, Rest Api, Social Media, Oauth, Https

In previous section we have learnt about how web servers work, scenario and things involved in HTTP request and responses. Let’s go ahead and learn why we should use REST API.

Howie Dorough Everybody GIF by BACKSTREET BOYS

Business logic can be completely independent of front-end code. Can be used by multiple clients avoiding re-writing. (Mobile app, website, desktop app…) Role based access in API layer than database layer. High load can be managed with the help of HTTP proxy server and cache.

There are numerous advantages of REST API, I will list out few below. (Please comment down if I missed anything).

How we should model a perfect API?

A meaningful API is a necessary thing required for any application to grow, no matter how complex business logic we write inside it, it should be meaningful when a newbie or an external person of an organization can easily understand when he just goes through the documentation.

Checkout JSONPlaceholder a mock API as an example.

An endpoint must handle only particular work and should have very less response time. You might be thinking what would be an ideal response time? Well we couldn’t predict it and it also depends heavily on the location of the server and internet speed of the user, let’s assume everything is fine and you’re running on stable internet connection with a healthy server, then any response under 100ms might be great. That time means nothing for humans but every millisecond shoots a lot for a computer, that’s how they are designed, to be fast and effective.

Let’s design a social media back-end, considering only user and posts data.

Users

Post API

This is okay, but where is security in this? Let’s learn that in the next article of this series, the Securing REST API with JWT — OAuth 2.0 protocol. (coming soon)
Using Dates in your Front End application
By: Nasreddine Skandrani
Tags: API, Front End Development, Rest Api, Backend Development

Short article to discuss the topic of Dates usage in Front End applications.

What you should be probably doing in your Front End?

Option 1

Using the format https://en.wikipedia.org/wiki/ISO_8601 to receive all dates from the Back End and send them back to it. Use UTC dates of course formatted in ISO.

If you want to learn more about why UTC and what to do if the Front End is not under your control, read here.

Like the database, to keep your API consistent, HTTP responses payloads should always be in UTC. However, your API should follow the robustness principle: Be conservative in what you do, be liberal in what you accept from others. Thus, your API should parse any timezone in the HTTP request body or URL parameters and not require UTC. Some APIs will default the absence of timezone information as UTC.

Option 2

Using timestamps to receive all dates from the Back End and send them back to it.

~ ~ ~ ~ ~ ~ ~ ~ ~

Note 1:

It’s more difficult to debug timestamp than ISO in the network tab of chrome :)

Note 2:

You don’t need to have a type Date received from the Back End in your DTO types. They can remain in string with the right format if you don’t do something special with them.

In my case personally, it’s Date that is used in the DTO. I find it more easy if i have to format to locale time later.

Thanks to my friend Amin Paks for the support in the topic.
In-Memory CSV Files For Automated Tests
By: Kwabena Asante
Tags: Csv, Rest Api, Unit Testing, Sofware Development, Python

In my line of work, we do build a lot of REST APIs for uploading and manipulating CSV files.

Our core stack is Python with Django Web framework, PostgreSQL database, Redis used as cache and RabbitMq as a message broker.

So what happened? With time I realized we didn’t have fast, reliable, independent and well isolated automated tests i.e. unit and end to end tests for these REST APIs.

I realized my colleagues were adding Sample CSV files in other to write automated tests for functionalities in these endpoints.

And to be able to run these tests in the CI/CD pipelines these CSV files were committed in to the version control system.

I felt this was wrong and our codebase was just getting bloated with assets which are not needed in our production environment.

Being a proactive Software Engineer I built a simple python library that allows you to generate in-memory CSV files to enhance writing of robust test cases.

The library is currently available on Pypi and also open for contributions on Github

But I still leave this open for your comments; whether to add Sample CSV files for your automated tests or use generated in-memory CSV files.

I will love to hear your opinion.
Sua API está bem documentada? Detalhes que precisamos observar
By: Tainara Reis
Tags: Documentação, Test, Rest Api, Testes De Software, API

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
A User Authentication Android App made in Android Studio
By: Harsh Kudtarkar
Tags: Java, UI, Android App Development, Rest Api

After some processing time, the Android Studio main window appears.

Now take a moment to review the most important files. First, be sure the Project window is open (select View > Tool Windows > Project) and the Android view is selected from the drop-down list at the top of that window. You can then see the following files:

app > java > com.example.userauthentication > MainActivity

This is the main activity. It’s the entry point for your app. When you build and run your app, the system launches an instance of this Activity and loads its layout.

app > res > layout > activity_main.xml

This XML file defines the layout for the activity's user interface (UI). It contains a TextView element with the text "Hello, World!"

app > manifests > AndroidManifest.xml

The manifest file describes the fundamental characteristics of the app and defines each of its components.

Gradle Scripts > build.gradle

There are two files with this name: one for the project, "Project: User Authentication" and one for the app module, "Module: app." Each module has its own build.gradle file, but this project currently has just one module. Use each module's build.gradle file to control how the Gradle plugin builds your app. For more information about this file, see Configure your build.

Before you run your first app, get your smart phone and enable USB debugging by following the instructions over here. After, enabling USB debugging, connect your smart phone to your PC and you are ready to go.

In Android Studio, select Run > Run ‘app’ or click the Run icon in the toolbar.

Congratulations on creating your very first app. But you are far from what we have to achieve. Next we need to create the rest of the applications.

Setting up the files:

Lets start with app > res > drawables. This is the directory where we will be storing all the graphical elements for our application. We are going to store three different categories of graphic elements.

Images. (filename: background.jpg, image.png)

Icon elements. (filenames: account.xml, email.xml, eye.xml, eye_off.xml, lock.xml)

Custom graphic file. (round_button_2.xml)

The images used here are for background and a logo in the logged-in session. You can use any image you like but be sure to use the same file name for the next part where we will be coding the back-end and creating activity layouts.

Icon elements are XML files for vector graphic icons used in our application. You can find and download these files from here.

The custom graphic file here is used for creating a rich look for our buttons in the application. It’s an XML file containing various tags and attributes specifying the properties that the button will have for its appearance.
REST APIs, SOAP vs REST APIs, REST APIs Smackdown!
Tags: API, Rest Api, Mainframe

APIs are a trending topic, energetically debated by business-people, IT managers, and developers alike. In this tutorial, I’ll describe the REST APIs (Application Programming Interface). So let’s look at an overview of REST API.

What is REST APIs?

REST stands for REpresentational State Transfer APIs. REST APIs are an architectural style defined to help create and organize distributed systems. REST, however, is the newcomer on the block and for web service access protocols. REST APIs objective is to provide a truly simple, lightweight method for accessing web services.

History of REST APIs.

Roy Fielding an American computer scientist has made tremendous contributions to the IT Industry, especially regarding the Internet, but according to my perception, his research thesis is the thing that received the most attention and highlights his name among a lot of people who otherwise wouldn’t have heard of him.

He was born in 1965 and he is one of the main authors of the HTTP protocol, the protocol that the entire Web infrastructure is based on.

In the year 2000, Fielding presented his doctoral dissertation, Architectural Styles and the Design of Network-based Software Architecture. In its, he coined the term REST, an architectural style for distributed hypermedia systems.

REST APIs Tasks.

Let’s look at some REST API tasks. The most REST (Representational State Transfer) services or most web services that are using REST APIs rely exclusively on obtaining the needed information using a URL. Therefore, REST APIs can use four different HTTP verbs to perform tasks.

GET, which is used to retrieve it. POST, which can be used to create. PUT, which can be used to update. DELETE, which is used to delete.

JSON stands for JavaScript Object Notation. JSON is a simple and language-independent way of formatting programming language data structures (numbers, arrays, hashes, and so on) as strings. JSON makes a lightweight alternative to XML-based approaches to data serialization, like XML Schema.

Example of JSON Feed.

“tags”: [“Office”, “Garden”]

SOAP vs REST.

Many developers found working with SOAP cumbersome and hard to use.

For example, working with SOAP in JavaScript meant writing a ton of code to perform extremely simple tasks because you’d have to create the required XML structure absolutely every time.

So to simplify that, REST relies on a simple URL, in most cases, as opposed to any kind of complex XML structuring.

So unlike SOAP, REST doesn’t have to use XML to provide the response. So you can find REST-based services that output the data in command-separated values or CSVs, JavaScript Object Notation, JSON, or in RSS, Really Simple Syndication. So the point is that you can obtain the output you need in a form that’s easy to parse within the language you need for your application using REST.
Building a Serverless REST API on AWS in Python
By: Aashray Jain
Tags: AWS Lambda, Rest Api, Dynamodb, Api Gateway, AWS

So far so good.

Let’s quickly write our code to finish our POST Operation from our Lambda.

import json

import boto3

from datetime import datetime def lambda_handler(event, context):



dynamodb = boto3.resource('dynamodb')



table = dynamodb.Table('REST')



eventDateTime = (datetime.now()).strftime("%Y-%m-%d %H:%M:%S")

userId = event['Id']

firstName = event['FirstName']

lastName = event['LastName']

age = event['Age']

hobbies = event['Hobbies']



try:



table.put_item(

Item={

'eventDateTime': eventDateTime,

'Id': userId,

'FirstName': firstName,

'LastName': lastName,

'Age': age,

'Hobbies': hobbies

}

)



return {

'statusCode': 200,

'body': json.dumps('Succesfully inserted the user info!')

}

except:

return {

'statusCode': 400,

'body': json.dumps('Error saving the user info')

}

Let’s quickly test our lambda with the following input.

{

"Id": "a1",

"FirstName": "Robert",

"LastName": "Downy",

"Age": 45,

"Hobbies": [

"Movies",

"Books"

]

}

Looks like everything is working fine. Phew!

Let’s move on to the final piece of the puzzle, linking this Lambda function to an API Gateway.

We’ll be working with “REST API Private” for our use-case.

Once you are finished with all the naming/description formalities, click on “Actions” and Create a POST Method. After that add your function name and Save the API Gateway-Lambda integration.

Post this, use the following payload for smoke testing.

{

"Id": "a2",

"FirstName": "Jack",

"LastName": "King",

"Age": 30,

"Hobbies": [

"Sports",

"Arts"

]

}

You should be able to see this record in DynamoDB table now!

Now let’s quickly follow the same steps and create GET, DELETE functions and get back to enjoying movies on Netflix.

GET Lambda Function:

import json

import boto3 def lambda_handler(event, context):

dynamodb = boto3.resource('dynamodb')

table = dynamodb.Table('REST')

response = table.scan()

return {

'statusCode': 200,

'body': response['Items']

}

DELETE Lambda Function:

import json

import boto3 def lambda_handler(event, context):



dynamodb = boto3.resource('dynamodb')

table = dynamodb.Table('REST')



userId = event['Id']

firstName = event['FirstName']



try:

response = table.delete_item(

Key={

'Id': userId,

'FirstName': firstName

}

)

return response

except Exception as e:

print(e)

return {

'statusCode': 400,

'body': json.dumps('Error deleting the user info')

}

NOTE: Since while creating our DynamoDB table, we defined both hash key and sort key, we need to add them both in our DELETE Function and DELETE Request!!!

Use the following JSON to test your DELETE Method.

{

"Id": "a2",

"FirstName": "Jack"

}

Eureka!

We have done it!

We have successfully built a Serverless REST API on AWS in Python!!
Using JWT as Authentication in API Gateway
By: Taufan Fadhilah Iskandar
Tags: Microservices, Jwt, Rest Api, Nodejs, Api Gateway

JWT logo

This is the last part of our journey to build simple microservice. Now we will give an authentication module to make our APIs secure.

What is JSON Web Token?

JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA or ECDSA.

When should you use JSON Web Tokens?

Here are some scenarios where JSON Web Tokens are useful:

Authorization : This is the most common scenario for using JWT. Once the user is logged in, each subsequent request will include the JWT, allowing the user to access routes, services, and resources that are permitted with that token. Single Sign On is a feature that widely uses JWT nowadays, because of its small overhead and its ability to be easily used across different domains.

: This is the most common scenario for using JWT. Once the user is logged in, each subsequent request will include the JWT, allowing the user to access routes, services, and resources that are permitted with that token. Single Sign On is a feature that widely uses JWT nowadays, because of its small overhead and its ability to be easily used across different domains. Information Exchange: JSON Web Tokens are a good way of securely transmitting information between parties. Because JWTs can be signed — for example, using public/private key pairs — you can be sure the senders are who they say they are. Additionally, as the signature is calculated using the header and the payload, you can also verify that the content hasn’t been tampered with.

You can read more about JWT, next what we will do is:

- Setup .env

- Create middleware

- Add middleware to route

- Run in Postman
Apex Code to Create Custom Field Programmatically
By: Ayub Ansari
Tags: Rest Api, Tooling, Apex, Custom Fields, Salesforce

DESCRIPTION

It’s very typical to get such a scenario when we need to create custom field programmatically. Previously, we used to use Metadata API for the same which was very costly.

But now, Tooling API provides an efficient way to achieve it. I’ve prototyped in below class. You can create custom fields as given below.

APPROACH

Below given code is metadata driven, so for each type of field,

You need to get the metadata. Below is a tip to get metadata.

You can get required metadata using workbench –> Rest Explorer and hit /services/data/v48.0/tooling/sobjects/CustomField/00N9000000DHfrM where ‘00N9000000DHfrM‘ is existing field with same data type. this call will return JSON response where you can extract metadata and manipulate as per your requirement.

where ‘00N9000000DHfrM‘ is existing field with same data type. this call will return JSON response where you can extract metadata and manipulate as per your requirement. You will need to create remote site setting for the given endpoint which is base URL of your salesforce org.

Copy the following utility apex class:

public class MetadataUtility{



public static void generateTextField(String objectAPIName, String fieldAPIName, String fieldDescription, String fieldLabel){

String metadata = '{"Metadata" : {"type" : "Text","description" : "'+fieldDescription+'", "inlineHelpText" : "","precision" : null,"label" : "'+fieldLabel+'","length" : 255,"required" : false}, "FullName" : "'+objectAPIName+'.'+fieldAPIName+'"}';



String responseBody = createField(metadata);

}



public static void generateFormulaField(String objectAPIName, String fieldAPIName, String fieldDescription, String fieldLabel, String retrunType, String validFormula){



String metadata = '{"Metadata" : {"type" : "'+retrunType+'","description" : "'+fieldDescription+'", "formula" : "'+String.escapeSingleQuotes(validFormula)+'","formulaTreatBlanksAs" : "BlankAsZero","label" : "'+fieldLabel+'"}, "FullName" : "'+objectAPIName+'.'+fieldAPIName+'"}';

String responseBody = createField(metadata);

system.debug(responseBody);

}



public static String createField(String metadata) {

HttpRequest request = new HttpRequest();

request.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionID());

request.setHeader('Content-Type', 'application/json');

request.setEndpoint(URL.getSalesforceBaseUrl().toExternalForm()+'/services/data/v46.0/tooling/sobjects/CustomField');

request.setMethod('POST');



request.setBody(metadata);



Http http = new Http();

HTTPResponse res = http.send(request);

return res.getBody();

}

}

Examples of Usage:

MetadataUtility.generateTextField(‘Account’, ‘Type_x__c’, ‘Text Field created by apex’, ‘Type (apex)’);

//Parameter “validFormula” is important and it should be correct and formatted to support JSON.
Build API Gateway with Nodejs for Microservice
By: Taufan Fadhilah Iskandar
Tags: Microservices, JavaScript, Rest Api, Expressjs, Nodejs

illustration for api gateway

This article is about how to build a API Gateway for our microservice. Previously we already build a Property Service and User Service, so you can follow from beginning.

What is an API Gateway?

An API gateway takes all API calls from clients, then routes them to the appropriate microservice with request routing, composition, and protocol translation. Typically it handles a request by invoking multiple microservices and aggregating the results, to determine the best path. It can translate between web protocols and web‑unfriendly protocols that are used internally.

In this article, our API gateway act is be a gateway from client to access our services. And also next article we will learn how to set the authentication in our API gateway and set the middleware as well.

Next, we will start to build an API Gateway with Nodejs with this following steps:

- Create Express project

- Setup .env

- Create apiAdapter

- Create service handler

- Register to routes

- Run in Postman