\chapter{HTTP based Communication}


\section{What is API}
API represents 'Application Programming Interface', that is to use programming method to create an interface so another programming language or another computing device could use it to do some calculation or get some information from it.

API is common in cloud computing, almost any cloud services in this world provides its API to their customer.

And also, the client needs to use APIs to communicate with its server. In this case, the API acts like a bridge linking multiple users and a central server.


\section{How to create an API server with Python}
Flask is a common tool for doing that. Django is also good. But for simplifying and asyncio supporting, I'll use a Flask-like tool 'sanic\cite{sanic}' as the tool we use.

\subsection{API server example}
\lstinputlisting[language=Python]{data/codes/5/1api_server_example.py}

\subsection{Test that server}
Now if you open your browser, go to \textbf{http://0.0.0.0:8000}, you'll see:
\begin{lstlisting}
        awesome people do awesome things.
\end{lstlisting}

If you go to \textbf{http://0.0.0.0:8000/api/v1/contacts?username=A}, you'll see:
\begin{lstlisting}
        [
          {
            "username": "A",
            "friends": [
              "A's friend 1",
              "A's friend 2"
            ]
          }
        ]
\end{lstlisting}

If you go to \textbf{http://0.0.0.0:8000/api/v1/contacts?username=B}, you'll see:
\begin{lstlisting}
        [
          {
            "username": "B",
            "friends": [
              "B's friend 1",
              "B's friend 2"
            ]
          }
        ]
\end{lstlisting}