Monday, 25 October 2021

FastAPI: Hello world application

In this post, I am going to explain simple hello world application.

 

Step 1: Import FastAPI class from fastapi library.

from fastapi import FastAPI

 

Step 2: Create a FastAPI instance.

app = FastAPI()

 

Step 3: Define path operation decorator.

@app.get("/")

 

The @app.get("/") tells FastAPI that the function right below is in charge of handling requests that go to:

a.   the path /

b.   using a get operation

 

That @something syntax in Python is called a "decorator". In general, a decorator takes a function below and do something with it. Similarly, all other verbs post, put, delete etc., are supported.

@app.post()

@app.put()

@app.delete()

@app.options()

@app.head()

@app.patch()

@app.trace()

 

 

Define main.py file with below content.

 

main.py

 

from fastapi import FastAPI

app = FastAPI()

# Create an endpoint
@app.get("/")
def about_me():
    return {"name" : "Hello World app", "version": "1.0.0"}

 

Step 2: Open terminal and execute the command ‘uvicorn main:app’.

$uvicorn main:app
INFO:     Started server process [56370]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)

 

uvicorn main:app

main : refers to the file name

app: refers to the object created inside of main.py with the line app = FastAPI().

 

Open the url ‘http://127.0.0.1:8000’ in browser, you will see the information about application.

 


Open the url ‘http://127.0.0.1:8000/docs’ in browser, you will see the swagger documentation.

 

 


 

 

You can see alternative documentation provided by https://github.com/Redocly/redoc at the url http://127.0.0.1:8000/redoc.

 

 



Can I return list, dictionary from the function ‘home’?

Yes

 

Can I return singular values like int, string from the function ‘home’?

Yes

 

Can I return custom objects from the function ‘home’?

Yes

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment