APIs are the way to expose your creations to the web. But it can be a bit frightening to learn how to create APIs from scratch, and sometimes it may even require you to re-write your code to match a certain framework. That’s why I built Asymmetric! With Asymmetric, you can add 1 line to any function you have already written and immediately transform it into an API. Let’s see an example! Imagine that you have the following method on your beautiful machine learning python file named predictor.py
:
def predict(attributes, values):
""" Predict something and return a list of possible values for the input data. """
predictions = MyModel.predict(attributes, values)
return predictions
Enter fullscreen mode Exit fullscreen mode
To transform that into an API, all you need to do is to add a decorator on top of your function! First, install Asymmetric with your terminal using pip
:
pip install asymmetric
Enter fullscreen mode Exit fullscreen mode
Now, back in your predictor.py
file, decorate your function!
from asymmetric import asymmetric
@asymmetric.router("/predict")
def predict(attributes, values):
""" Predict something and return a list of possible values for the input data. """
predictions = MyModel.predict(attributes, values)
return predictions
Enter fullscreen mode Exit fullscreen mode
To run your API, just use the run
command from your terminal! Remember to target the file containing your decorated function! (don’t include the .py
extension):
asymmetric run predictor
Enter fullscreen mode Exit fullscreen mode
And that’s it! You have succesfully transformed your function into an API! You can now make POST
requests to http://localhost:8000/predict
, passing in the request body the parameters of the function! Let’s see an example using httpx
!
import httpx
parameters = {
"attributes": ["color", "texture"],
"values": [15.7, 8]
}
response = httpx.post("http://localhost:8000/predict", json=parameters)
print(response.json())
Enter fullscreen mode Exit fullscreen mode
You should see the result of your prediction! Asymmetric has a ton of other features, such as automagic documentation and callback endpoints! Go check out the project! If you have any questions, don’t hesitate to ask them! And if you like the project, a star would be massively appreciated ️
原文链接:Tool for transforming any function into an API in seconds!
暂无评论内容