Fast & Easy Python APIs Using FastAPI | by Billy Bonaros | Towards Data Science

FastAPI is a modern, python-based high-performance web framework used to create Rest APIs. Its key features are that is fast, up to 300% faster to code, fewer bugs, easy to use, and production-friendly.
The only con about Fast API is that it’s relatively new and its community is not so big as other frameworks like Flask but I think it will grow fast as many companies like Microsoft, Netflix, and Uber are already using it.
In this post, I will show you how to create some simple GET and POST APIs using Fast API.
pip install fastapi
We will also need an ASGI server, for production such as Uvicorn.
pip install uvicorn
Let’s get started by creating the simplest API. It will return a JSON with the message “Hello World”.
Create a “main.py” file with the following code.
#import FastAPIfrom fastapi import FastAPI #create a FastAPI instanceapp = FastAPI() #create a path operation@app.get(“/”)#define the path operation functiondef root(): return {“message”: “Hello World”}
As you can see, there are 4 main steps to create an API with FastAPI. The first step is to import it, and then to create a FastAPI instance(in our case it’s called app).
After that, we have to create a path operation. That means we have to set the URL path(in our case is ‘/’ but we can set anything like ‘/helloworld’) and its operation. By operation we mean the HTTP methods like GET, POST, PUT and DELETE(in our case the operation is get).
Lastly, we have to define the path operation function. In other words, a function that returns what we want to get from our API(in our case is a JSON with the message Hello World.
Now, navigate to the main.py’s folder through the terminal and run the following:
uvicorn main:app --reload
You should see the following output.
That means that our API is running at http://127.0.0.1:8000. Let’s see what we got.
Let’s say we want to create a GET API that takes as input two numbers and returns their sum. To add the parameters you just have to put them as the parameters of the path operation function.
from fastapi import FastAPI app = FastAPI() @app.get("/addition")def sum(a, b):    return {"Result": a+b}
You can pass parameters to the URL by adding the symbol “?” then the parameters with the symbol “&” between them. Let’s try the following:
http://127.0.0.1:8000/addition?a=12&b=13
Easy as that. You can also set the type of the parameters like integer or string so if the user puts a different type, it will return a warning.
@app.get("/addition")def sum(a:int, b:int):    return {"Result": a+b}
Let’s out a string and see what we will get.
http://127.0.0.1:8000/addition?a=12&b=aa
I will show you how you can create a POST API that expects as input a JSON file. Let’s see an easy example.
from fastapi import FastAPIfrom pydantic import BaseModel app = FastAPI()  class inputs(BaseModel):    a:int    b:int    c:int    d:int                  @app.post('/show_data')def show_data(data: inputs):    return({"data":[data.a,data.b,data.c,data.d]})
We have to import BaseModel and create a BaseModel class that contains the variables of the JSON file(a, b, c, d in our example). Then, we have to set the class to a variable inside the operation function(data: inputs in our case). Now we can access the variable inside the function using the name of the class variable and the name of its variables like data.a to access the variable a, data.b, etc.
FastAPI provides us automatically with SwaggerUI which is a genius and very helpful UI that allows us to visualize and interact with the API’s resources. It can also be used for testing even for POST APIs like the above. You can access it by adding the /docs in your APIs URL.
http://127.0.0.1:8000/docs
As you can see in the video above, we’ve tested our API and it runs perfectly.
For this example, we will train a simple ML model to predict the type of irises (Setosa, Versicolour, and Virginica) using the famous Iris Dataset. Then we will create a POST API using FastAPI that will take as input the features and will return the prediction.
First things first, let’s train our model and save it to a pickle file.
from sklearn import datasetsfrom sklearn.linear_model import LogisticRegressionimport pandas as pdiris = datasets.load_iris()features=pd.DataFrame(iris['data'])target=iris['target']model=LogisticRegression(max_iter=1000)model.fit(features,target) import picklepickle.dump(model, open('model_iris', 'wb'))
Now, we are ready to create our API.
from fastapi import FastAPIfrom pydantic import BaseModel app = FastAPI()  class iris(BaseModel):    a:float    b:float    c:float    d:float         from sklearn.linear_model import LogisticRegressionimport pandas as pdimport pickle#we are loading the model using picklemodel = pickle.load(open('model_iris', 'rb'))               @app.post('/make_predictions')async def make_predictions(features: iris):    return({"prediction":str(model.predict([[features.a,features.b,features.c,features.d]])[0])})
Now If you feed the API above with the following JSON you will get a prediction.
{  "a": 1.1,  "b": 3.3,  "c": 5,  "d": 1}{  "prediction": "2"}
FastAPI is one of the best Python frameworks for Rest APIs because it’s fast, easy, and production-friendly. Its community will grow fast as companies like Netflix, Uber, and Microsoft are already using it. You don’t need anything more than we cover in this post to start, so start experiment with it!
Originally published at https://predictivehacks.com.