Creating First REST API with FastAPI

FastAPI :
FastAPI is modern Web Framework . It is used for building API and is very easy to learn .

Features of FastAPI :

  • High Performance than many Web Frameworks, faster than Node.js, etc .
  • Easy to Develop API’s
  • Production Ready
  • Well Documentation to learn code fast
  • Swagger UI to form API Documentation
  • Avoid Redundancy of Code
  • Easy Testing
  • Support for GraphQL, Background Fetching, Dependency Injection

CREATING REST API USING FastAPI :

  • Install Python 3 and pip/pip3 according to your Operating System
  • Now, install fastapi using pip or pip3 :

       pip install fastapi
    
  • Install the uvicorn which is the Asynchronous Gateway Interface for your Server using :



      pip install uvicorn
    
  • Now create a main.py file and import fastapi, also create a server

      from fastapi import FastAPI
      app = FastAPI()
    
  • Now, let’s add the code for sample get request as shown below :

     @app.get("/")
     def read_root():
        return {"Hello": "World"}
    
  • Hence, the main.py file will look like :

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    from fastapi import FastAPI
    app = FastAPI()
     
    @app.get("/")
    def first_example():
        """
           GFG Example First Fast API Example 
        """
       return {"GFG Example": "FastAPI"}

    chevron_right

    
    

  • Now, start the server using

    uvicorn main:app --reload
    
  • Now open the browser and open http://localhost:8000/docs or http://127.0.0.1:8000/docs
    You will be able to see the Swagger UI Home page as below :
    Swagger UI
  • Expand the “First Example” :
    Expanded Swagger UI
  • Now try to Execute the API, you will get the success status with 200 code .
    The Response will be {“GFG Example”: “FastAPI”} as shown below :
    First Example API Execution
My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.